<template>
  <div class="app-container">
    <div class="formDesigner">
      <!-- 管理页面 -->
      <div v-show="!showDesigner" class="managePage">
        <!-- 左侧表单分类列表 -->
        <div class="leftTypes">
          <div class="logo-wrapper" style="border-bottom: 0px">
            <div class="logo" @click="changeType('')">表单分类</div>
          </div>
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            size="small"
            style="width:90%;margin:10px 0"
            v-model="inputValue"
            @input="searchInputChange"
            clearable
          >
          </el-input>
          <div v-if="listRst.length===0" class="formTypeEmpty"> 暂无表单分类</div>
          <div class="formTypeItems">
            <div v-for="(item,index) in listRst" :key="index" :class="{formTypeItem:true,active:item.value===activeName}"
              @click="changeType(item.value)">
              <span :title="item.label" class="menuTitle"> <i class="el-icon-folder" style="marginRight:8px;"></i>{{item.label}}</span>
            </div>
          </div>
        </div>
        <!-- 右侧表单数据列表 -->
        <div class="rightContent">
          <!-- 顶部表单搜索和表单操作按钮 -->
          <div>
            <div style="marginBottom: 20px;display: inline-block">
              <el-input v-model="searchText" placeholder="请输入要查询的关键字" size="small" class="keywordInput" clearable
                style="width: 260px;marginRight: 40px"
                @keyup.enter.native="searchChange">
              </el-input>
              <el-button type="primary" icon="el-icon-search" size="small" @click="searchChange">搜索</el-button>
              <el-button size="small" icon="el-icon-refresh" @click="resetSeach">重置</el-button>
            </div>
            <div style="float:right;marginBottom: 20px">
              <el-button type="primary" icon="el-icon-plus" size="small" @click="addForm">新增</el-button>
              <el-button type="danger" plain size="small" icon="el-icon-delete" @click="multiDelForm" :disabled="selectionLength===0">批量删除</el-button>
              <el-button size="small" icon="el-icon-view" @click="viewForm" :disabled="selectionLength!==1">预览表单</el-button>
              <el-button size="small" icon="el-icon-document-checked" @click="useForm" :disabled="selectionLength!==1||isEnable===0">启用表单</el-button>
              <el-button size="small" icon="el-icon-document-delete" @click="unuseForm" :disabled="selectionLength!==1||isEnable===1">禁用表单</el-button>
              <!-- <el-button size="small" @click="historyRecord" :disabled="selectionLength!==1">历史记录</el-button> -->
              <el-button size="small" icon="el-icon-menu" @click="()=>{dialogTableVisible = true;tableTypeLoading=true;getTypeList()}">分类管理
              </el-button>
              <el-tooltip class="item" effect="dark" content="显隐" placement="top">
                <el-button icon="el-icon-s-operation" circle @click="showHide(false)"></el-button>
              </el-tooltip>
            </div>
          </div>
          <el-table ref="multipleTable" :data="tableData" stripe class="tableInfo" size="small" highlight-current-row
            @selection-change="handleSelectionChange" v-loading="tableLoading" row-key="id">
            <el-table-column type="selection" width="34" align="center" :reserve-selection="true">
            </el-table-column>
            <el-table-column label="序号" width="80" align="center" v-if="!showHideData[0].hide">
              <template slot-scope="scope">
                <span>{{scope.$index+(page.pageNo-1)*page.pageSize+1}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="formName" label="表单名称" align="center" show-overflow-tooltip
              v-if="!showHideData[1].hide">
            </el-table-column>
            <el-table-column prop="sysCategory.categoryName" label="表单分类" align="center" show-overflow-tooltip
              v-if="!showHideData[2].hide">
            </el-table-column>
            <el-table-column prop="isEnable" label="启用状态" align="center" show-overflow-tooltip
              v-if="!showHideData[3].hide">
              <template slot-scope="scope">
                <span slot="reference" v-if="scope.row.isEnable === 0" style="display:flex; justify-content:center; align-items: center;">
                  <i class="dotClass" style="background-color: #67C23A;margin-right: 5px;" ></i>已启用
                </span>
                <span slot="reference" v-else style="display:flex; justify-content:center; align-items: center;">
                  <i class="dotClass" style="background-color:gray;margin-right: 5px;"></i>未启用
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="isReference" label="引用状态" align="center" show-overflow-tooltip
              v-if="!showHideData[4].hide">
              <template slot-scope="scope">
                <span slot="reference" v-if="scope.row.isReference === 1" style="display:flex; justify-content:center; align-items: center;">
                  <i class="dotClass" style="background-color: #1890ff;margin-right: 5px;" ></i>已引用
                </span>
                <span slot="reference" v-else style="display:flex; justify-content:center; align-items: center;">
                  <i class="dotClass" style="background-color:gray;margin-right: 5px;"></i>未引用
                </span>
              </template>
              <!-- <template slot-scope="scope">
                {{scope.row.isReference===1?'已引用':'未引用'}}
              </template> -->
            </el-table-column>
            <el-table-column prop="creatorName" label="创建人" align="center" show-overflow-tooltip
              v-if="!showHideData[5].hide">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip
              v-if="!showHideData[6].hide">
              <template slot-scope="scope">{{getDateTime(scope.row.createTime)}}</template>
            </el-table-column>
            <el-table-column prop="formDesc" label="备注" align="center" show-overflow-tooltip
              v-if="!showHideData[7].hide">
              <template slot-scope="scope">
                {{scope.row.formDesc?scope.row.formDesc:'-'}}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template slot-scope="scope">
                <el-button size="small" type="text" icon="el-icon-edit" @click="editForm(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="text" icon="el-icon-document-copy" @click="copyForm(scope.row)">
                  复制
                </el-button>
                <el-button size="small" type="text" style="color:red" icon="el-icon-delete" @click="delForm(scope.row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination background :layout="layout" :total="pageTotal" :page-size="page.pageSize"
            :current-page="page.pageNo" :page-sizes="pageSizes" style="float:right;marginBottom:20px;"
            @size-change="sizeChange" @current-change="currentChange">
          </el-pagination>
        </div>
      </div>
      <!-- 新增--表单设计页面 -->
      <div v-show="showDesigner">
        <!-- 表单设计顶部 -->
        <el-row :gutter="24" style="border-bottom:1px solid #e8eaec;padding:0 0 10px 0">
          <el-col :span="18">
            <div class="designHeader">
              <div class="designStep">
                <div v-for="(item,index) in steps" :key="index" class="designStepItem">
                  <div class="designStepLine" :style="{border:index>0?'1px solid rgba(0,0,0,0.3)':'1px solid white'}">
                  </div>
                  <div class="designStepIndex" :style="{background:index<stepNum?'#409EFF':'rgba(0,0,0,0.3)'}">
                    {{index+1}}</div>
                  <div class="designStepTitle" :style="{
                      color:
                        index < stepNum ? '#1890FF' : 'rgba(0,0,0,0.3)',
                    }"> {{item}}</div>
                </div>
              </div>
            </div>
          </el-col>
          <el-col :span="6" style="textAlign:right;">
            <el-button v-show="stepNum>1" @click="nextStep('sub')">上一步</el-button>
            <el-button v-show="stepNum<3" @click="nextStep('plus')" type="primary">下一步</el-button>
            <el-button v-show="stepNum===3" type="primary" @click="finishForm">完成</el-button>
            <el-button type="danger" @click="closeDesign" plain>关闭</el-button>
          </el-col>
        </el-row>
        <!-- 步骤1---基础信息 -->
        <div v-show="stepNum===1" class="basicInfo">
          <el-form :model="formInfo.basic" ref="basicForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="表单名称" prop="formName"
              :rules="[{required:true,message:'请输入表单名称',trigger:'blur'},{validator:formNameValidator,trigger:'blur'}]">
              <el-input v-model="formInfo.basic.formName" placeholder="请输入表单名称"></el-input>
            </el-form-item>
            <el-form-item label="表单分类" prop="categoryId" :rules="[{required:true,message:'请选择表单分类',trigger:'change'}]">
              <el-select v-model="formInfo.basic.categoryId" placeholder="请选择表单分类" filterable style="width:100%;" clearable>
                <el-option v-for="(item,index) in formTypes" :label="item.label" :key="index" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="formDesc">
              <el-input type="textarea" v-model="formInfo.basic.formDesc" :rows="5" maxlength="200" show-word-limit
                placeholder="请输入备注">
              </el-input>
            </el-form-item>
          </el-form>
        </div>
        <!-- 步骤2---表单设计 -->
        <div v-show="stepNum===2" style="marginTop:10px;">
          <form-editor ref="design" :isEdit="formInfo.id!==''" @updateFieldId="updateFieldId" @deleteItem ="deleteItem"
            :idDefault="fieldId" :newFormName="newFormName" @deleteChildData="deleteChildData">
          </form-editor>
        </div>
        <!-- 步骤3---表结构配置 -->
        <div v-show="stepNum===3" class="formConfig tableForm" v-loading="tableLoading">
          <el-form :model="formInfo.dataSource" ref="datasource" style="margin-bottom: 20px">
            <el-form-item label="数据库选择" prop="name" :rules="[{required:true, message: '请选择数据库', trigger: 'change'}]">
              <el-select v-model="formInfo.dataSource.name" placeholder="请选择数据库" disabled>
                <el-option label="本地数据库" value="awesome"></el-option>
                <el-option label="远程数据库" value="remote"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <!-- <div class="tooltipText">
              *({{formInfo.nameData[0].tableName?}})为主表,字段名点击进行名称修改,数据格式默认为varchar
            </div> -->
          <el-form :model="formInfo" ref="tableInfo">
            <!-- 主表字段 -->
            <el-table row-key="tableRemark" :data="formInfo.nameData" stripe size="small" class="tableConfig" :default-expand-all="true" :expand-row-keys="expandKeys">
                <el-table-column type="expand">
                 <template>
                    <el-table
                        :data="formInfo.fieldData.slice((configPage.pageNo - 1) * configPage.pageSize, configPage.pageNo * configPage.pageSize)"
                        size="small" style="margin-left: 58px;width: 93%;margin-top:10px;">
                        <el-table-column prop="name" label="字段名" align="center">
                            <template slot="header">
                            <span>
                                <el-tooltip class="item" effect="dark" content="*字段名以小写字母开头，不能有大写字母、汉字、空格" placement="top">
                                <i class="el-icon-warning-outline" style="color:red;paddingRight:10px;"></i>
                                </el-tooltip>字段名
                            </span>
                            </template>
                            <template slot-scope="scope">
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.name`"
                                :rules="[{required:true,message:'请输入字段名',trigger:'blur'}, {validator:fieldNameValidator,trigger:'blur'}]">
                                <el-input v-model.trim="scope.row.name" @change="validateForm">
                                </el-input>
                            </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column prop="length" label="长度(字符)" align="center">
                            <template slot="header">
                            <span>
                                <el-tooltip class="item" effect="dark" content="*已发布表单编辑时，修改数值不能小于上次数值" placement="top">
                                <i class="el-icon-warning-outline" style="color:red;paddingRight:10px;"></i>
                                </el-tooltip>长度(字符)
                            </span>
                            </template>
                            <template slot-scope="scope">
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-if="scope.row.format === 'varchar'"
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:(rule,value,callback)=>{
                                  lengthValidator(rule,value,callback,scope.row,formInfo)},trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}">
                                </el-input>
                            </el-form-item>
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-else-if="scope.row.format === 'longtext'"
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator2,trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                </el-input>
                            </el-form-item>
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-else-if="scope.row.format === 'int'"
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator2,trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                </el-input>
                            </el-form-item>
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-else-if="scope.row.format === 'double' || scope.row.format === 'decimal'"
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator3,trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                </el-input>
                            </el-form-item>
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-else-if="scope.row.format === 'datetime'"
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator2,trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                </el-input>
                            </el-form-item>
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-else-if="scope.row.format === 'time'"
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator2,trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}" disabled>
                                </el-input>
                            </el-form-item>
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.length`"
                                v-else
                                :rules="[{required:true,message:'请输入字段长度',trigger:'blur'},{validator:lengthValidator3,trigger:'blur'}]">
                                <el-input v-model="scope.row.length" @focus="()=>{currentLength = scope.row}"></el-input>
                            </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column prop="format" label="数据格式" align="center">
                            <template slot-scope="scope">
                            <el-form-item :prop="`fieldData.${scope.$index+(configPage.pageNo-1)*configPage.pageSize}.format`">
                                <el-select filterable remote disabled v-model="scope.row.format" @focus="()=>{currentLength = scope.row}" @change="changeFormat(scope.row.format,scope.$index)">
                                <el-option v-for="(item,index) in dicData" :key="index" :label="item.label" :value="item.value">
                                </el-option>
                                </el-select>
                            </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column prop="desc" label="备注(标题)" align="center">
                            <template slot-scope="scope">
                            <el-form-item :prop="`fieldData.${scope.$index}.desc`">
                                <el-input v-model="scope.row.desc" :disabled="true"></el-input>
                            </el-form-item>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination background :layout="layout" :total="formInfo.fieldData.length" :page-sizes="pageSizes"
                    :current-page="configPage.pageNo" :page-size="configPage.pageSize" style="float:right;marginBottom:20px;"
                    @size-change="configSizeChange" @current-change="configCurrentChange">
                    </el-pagination>
                 </template>
                </el-table-column>
              <el-table-column prop="tableName" label="表名" align="center">
                <template slot="header">
                  <span>
                    <el-tooltip class="item" effect="dark" content="*表名以小写字母开头，不能有大写字母、汉字、空格" placement="top">
                      <i class="el-icon-warning-outline" style="color:red;paddingRight:10px;"></i>
                    </el-tooltip>表名
                  </span>
                </template>
                <template slot-scope="scope">
                  <el-form-item :prop="`nameData.${scope.$index}.tableName`"
                    :rules="[{required:true,message:'请输入表名',trigger:'blur'},{validator:tableNameValidator,trigger:'blur'}]">
                    <el-input v-model.trim="scope.row.tableName" placeholder="示例：table033378"></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="tableRemark" label="备注" align="center">
                <template slot-scope="scope">
                  <el-form-item :prop="`nameData.${scope.$index}.tableRemark`">
                    <el-input v-model="scope.row.tableRemark" placeholder="备注" disabled></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
            <!-- 子表单字段 -->
            <div v-for="(item, index) in formInfo.subFormListData" :key="index">
                <ExpandTable :allComponments="$refs.design.drawingList" :formId="formInfo.id" :allList="formInfo.subFormListData" :updateFlag="updateFlag" :ref="'childTableInfo'+ index" :formInfo="formInfo" :subFormListData="[...item]" @changeCountFunc="changeCountFunc" @changeFormat="tableChangeFormat"></ExpandTable>
            </div>
          </el-form>
        </div>
      </div>
      <!-- 表单预览 -->
      <el-dialog title="表单预览" :visible.sync="dialogPreviewVisible" :fullscreen="fullScreen" width="640px">
         <span slot="title" class="el-dialog__title">
         表单预览
           <i class="el-icon-full-screen" v-if="!fullScreen" @click="()=>{fullScreen = true}" style="float:right;marginRight:30px;margin-top: 3px"></i>
           <i class="el-icon-aim" v-else @click="()=>{fullScreen = false}" style="float:right;marginRight:30px;;margin-top: 3px"></i>
         </span>
          <div style="display:flex;justifyContent:center;margin-top:20px">
        <parser :form-conf="formConfData" v-if="dialogPreviewVisible" status="add"
          :originData="originData" :style="{width:fullScreen?'80%':'100%'}" @cancel="()=>{dialogPreviewVisible=false}" />
        </div>
      </el-dialog>
      <!-- 历史记录 -->
      <el-dialog title="历史记录" :visible.sync="dialogHistoryVisible">
        <el-table ref="historyTable" :data="historyData" stripe size="small" highlight-current-row>
          <el-table-column prop="operation" label="表单名称" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template>
              <el-button size="small" type="text">
                <el-link type="danger">删除</el-link>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
      <!-- 列显隐 -->
      <el-drawer :visible.sync="drawer" direction="rtl">
        <span slot="title" style="fontSize:18px;font-weight:500;color: #262626;">列显隐</span>
        <el-table :data="isType?showHideTypeData:showHideData" size="small" border style="width:80%;marginLeft:10%;">
          <el-table-column prop="columnName" label="列名" align="center">
          </el-table-column>
          <el-table-column prop="hide" label="隐藏" align="center">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.hide"></el-checkbox>
            </template>
          </el-table-column>
        </el-table>
      </el-drawer>
      <!-- 表单分类管理弹窗 -->
      <el-dialog title="表单分类管理" class="upload-dialog" :visible.sync="dialogTableVisible" width="1000px">
        <div style="float:right;margin:10px 0;">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="editType">新增</el-button>
          <el-tooltip class="item" effect="dark" content="显隐" placement="top">
            <el-button icon="el-icon-s-operation" circle @click="showHide(true)"></el-button>
          </el-tooltip>
        </div>
        <el-table :data="formTypeData" stripe style="width: 100%;marginBottom:20px;" size="small"
          v-loading="tableTypeLoading" highlight-current-row border>
          <el-table-column label="序号" width="80" align="center" v-if="!showHideTypeData[0].hide">
            <template slot-scope="scope">
              <span>{{scope.$index+(typePage.pageNo-1)*typePage.pageSize+1}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="categoryName" label="表单分类名称" align="center" v-if="!showHideTypeData[1].hide"
            show-overflow-tooltip>
          </el-table-column>
          <!-- <el-table-column prop="categoryCode" label="表单分类编码" align="center" v-if="!showHideTypeData[2].hide"
            show-overflow-tooltip>
          </el-table-column> -->
          <el-table-column prop="categorySpell" label="简拼" align="center" v-if="!showHideTypeData[2].hide"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="categoryOrder" label="排序" align="center" v-if="!showHideTypeData[3].hide"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="categoryRemarks" label="备注" align="center" v-if="!showHideTypeData[4].hide"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="small" type="text" @click="editType(scope.row)" icon="el-icon-edit">
                编辑
              </el-button>
              <el-button size="small" type="text" @click="delType(scope.row)" style="color:red" icon="el-icon-delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination background :layout="layout" :total="typePageTotal" :page-size="typePage.pageSize"
          :current-page="typePage.pageNo" :page-sizes="pageSizes" style="float:right;marginBottom:20px;"
          @size-change="typeSizeChange" @current-change="typeCurrentChange">
        </el-pagination>
        <span slot="footer" class="dialog-footer">
        </span>
      </el-dialog>
      <!-- 新增/编辑表单分类弹窗 -->
      <el-dialog :title="formTypeNew.id?'编辑表单分类':'新增表单分类'" :visible.sync="dialogTypeVisible" width="500px">
        <el-form :model="formTypeNew" ref="typeNewForm" label-width="120px" class="demo-ruleForm">
          <el-form-item label="表单分类名称" prop="categoryName"
            :rules="[{required:true,message:'请输入分类名称',trigger:'blur'},{validator:typeNameValidator,trigger:'blur'}]">
            <el-input v-model="formTypeNew.categoryName" placeholder="请输入分类名称"></el-input>
          </el-form-item>
          <!-- <el-form-item label="表单分类编码" prop="categoryCode"
            :rules="[{required:true,message:'请输入分类编码',trigger:'blur'},{validator:typeCodeValidator,trigger:'blur'}]">
            <el-input v-model="formTypeNew.categoryCode" placeholder="请输入分类编码"></el-input>
          </el-form-item> -->
          <el-form-item label="排序" prop="categoryOrder"
            :rules="[{required:true,message:'请输入排序',trigger:'blur'},{validator:sortValidator,trigger:'blur'}]">
            <el-input-number v-model="formTypeNew.categoryOrder" controls-position="right" :min="0" style="width:100%;">
            </el-input-number>
          </el-form-item>
          <el-form-item label="备注" prop="categoryRemarks">
            <el-input type="textarea" v-model="formTypeNew.categoryRemarks" :rows="5" maxlength="200" show-word-limit
              placeholder="请输入备注">
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="()=>{this.dialogTypeVisible = false}">取 消</el-button>
          <el-button type="primary" @click="saveType">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 同步数据库方式选择弹窗 -->
      <el-dialog title="同步数据库" :visible.sync="dialogConstructorVisible" width="500px">
        <el-radio-group v-model="updateTableType">
          <el-radio label="normal">普通同步(保留表结构)</el-radio>
          <el-radio label="force">强制同步(删除表，重新生成)</el-radio>
        </el-radio-group>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="()=>{this.dialogConstructorVisible = false;this.isFinish=false}">取 消</el-button> -->
          <el-button @click="cancelTableConstructor">取 消</el-button>
          <el-button type="primary" @click="updateTableConstructor">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import { reorganizationParam } from '@/utils/index'
  import Pinyin from '@/utils/ChinesePY'
  import FormEditor from './components/formEditor'
  import Parser from './components/parser'
  import ExpandTable from './ExpandTable.vue'
  // import { Loading } from 'element-ui';
  import {
    saveIdGlobal
  } from '@/utils/db'
  import {
    addCategory,
    editCategory,
    delCategory,
    getAllCategory,
    getPageCategory,
    createTable,
    updatatablecolumn,
    addField,
    deleteField,
    addFormInfo,
    editFormInfo,
    delFormInfo,
    getFormExist,
    getPageFormInfo,
    enableForm,
    disableForm,
    getTableListExcludeForm,
    multiDel,
    alterTable,
    createtablelist,
    savelist,
    editlist,
    deleteAllField
  } from '../../../api/custom/formDesigner'
  import {
    formConf
  } from '@/components/generator/config'

  //文本类型组件tag
  const textTypes = ['el-input', 'tinymce', 'my-select', 'my-radio-group', 'my-cascader','my-region', 'my-checkbox-group',
    'el-switch', 'el-color-picker', 'el-time-picker', 'el-date-picker', 'getMapPoint', 'el-upload','signature'
  ];
  //数字类型组件tag
  const intTypes = ['el-input-number','el-number', 'el-slider', 'el-rate'];
  //不添加默认规则组件tag-icon
  const noRules = ['select', 'radio', 'cascader', 'checkbox', 'switch', 'date-range', 'time-range', 'upload', 'user',
    'post', 'depart','tree-table'
  ];
  export default {
    name: 'formdesigner',
    components: {
      FormEditor,
      Parser,
      ExpandTable
    },
    data() {
      return {
        newFormName: '',
        searchFormData: {},
        updateFlag: false,
        showTableSetting: false,
        inputValue: "", //输入框的值
        listRst:{},//筛选之后的列表数据
        changeCount: 0,
        expandKeys: [],
        noShowDefaultList: ['Subform', 'el-tabs', 'TitleLine', 'TitleLine', 'Steps', 'el-switch', 'el-collapse', 'el-card', 'UsersSelector', 'DepartmentSelection', 'PostSelection', 'signature'],
        activeName: '', //当前选择表单分类
        stepNum: 1, //当前设计步骤
        steps: ['基础信息', '表单设计', '表结构配置'], //步骤名称
        //字段数据类型
        dicData: [{
            label: '文本',
            value: 'varchar'
          },
          {
            label: '长文本',
            value: 'longtext'
          },
          {
            label: '整数',
            value: 'int'
          },
          {
            label: '小数',
            value: 'double'
          },
          {
            label: '小数-高精度',
            value: 'decimal'
          },
          {
            label: '时间日期',
            value: 'datetime'
          },
          {
            label: '时间',
            value: 'time'
          },
        ],
        showDesigner: false, //显示表单设计
        tableLoading: false, //表格加载
        tableTypeLoading: false, //表单分类表格加载
        dialogEditVisible: false, //显示表单编辑
        dialogPreviewVisible: false, //显示表单预览
        dialogHistoryVisible: false, //显示表单历史记录
        drawer: false, //列显隐
        dialogTableVisible: false, //显示表单分类管理
        dialogTypeVisible: false, //显示新增表单分类
        dialogConstructorVisible: false, //显示表结构修改弹窗
        searchText: '', //关键字搜索
        isType: false, //区分是表单还是表单分类，表单分类列显隐true，表单列显隐false
        layout: 'prev, pager, next,sizes,jumper', //分页显示布局
        pageSizes: [10, 20, 30, 50], //分页显示每页条数选择
        pageTotal: 3, //表单总条数
        typePageTotal: 1, //表单分类总条数
        page: {
          pageNo: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        }, //表单分页配置
        typePage: {
          pageNo: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        }, //表单分类分页配置
        configPage: {
          pageNo: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        }, //数据表字段分页配置
        formTypes: [], //表单分类
        //表单设计数据
        formInfo: {
          id: '', //表单id
          basic: {
            formName: '', //表单名
            categoryId: '', //表单分类
            formDesc: '' //表单描述
          }, //表单基础信息
          formJsonUser: {
            fields: []
          }, //表单配置
          dataSource: {
            name: 'awesome' //乔宇
          }, //数据源选择
          nameData: [{
            tableName: '', //表名
            tableRemark: '' //描述
          }], //数据库表基础信息
          fieldData: [], //数据库表字段
          subFormListData: [], // 子表单数据库表展示方式()
        },
        tableData: [], //表单数据
        //列显隐
        showHideData: [{
            columnName: '序号',
            hide: false
          },
          {
            columnName: '表单名称',
            hide: false
          },
          {
            columnName: '表单分类',
            hide: false
          },
          {
            columnName: '启用状态',
            hide: false
          },
          {
            columnName: '引用状态',
            hide: false
          },
          {
            columnName: '创建人',
            hide: false
          },
          {
            columnName: '创建时间',
            hide: false
          },
          {
            columnName: '备注',
            hide: false
          }
        ],
        //历史数据，假数据，暂未开发
        historyData: [{
            operation: '新增',
            createTime: '2022-03-03 13:33:33'
          }, {
            operation: '修改',
            createTime: '2022-03-04 13:33:33'
          },
          {
            operation: '修改',
            createTime: '2022-03-06 13:33:33'
          },
          {
            operation: '修改',
            createTime: '2022-03-08 13:33:33'
          },
          {
            operation: '修改',
            createTime: '2022-03-13 10:03:20'
          }
        ],
        //表单分类列显隐
        showHideTypeData: [{
            columnName: '序号',
            hide: false
          },
          {
            columnName: '表单分类名称',
            hide: false
          },
          // {
          //   columnName: '表单分类编码',
          //   hide: false
          // },
          {
            columnName: '简拼',
            hide: false
          },
          {
            columnName: '排序',
            hide: false
          },
          {
            columnName: '备注',
            hide: false
          }
        ],
        formTypeData: [], //表单分类数据
        //表单分类新增/编辑数据
        formTypeNew: {
          id: '',
          categoryName: '',
          // categoryCode: '',
          categorySpell: '',
          categoryOrder: 0,
          categoryRemarks: ''
        },
        formEditData: [], //表单信息编辑原有字段
        formEditTableData: [], // 子表单编辑原有字段
        addFields: [], //表单信息编辑新添加字段
        alterData: [], //表单编辑修改字段
        addTableFieldsMap: new Map(), // 存储新增字段的map
        alterTableDataMap: new Map(), // 存储编辑字段的map
        formConfData: {}, //表单配置json
        multipleSelection: [], //多选
        formName: '', //当前编辑表单名称
        tableName: '', //当前编辑表单数据库表名
        categoryName: '', //当前编辑表单分类名称
        // categoryCode: '', //当前编辑表单分类编码
        isEnable: '', //启用禁用表单标识
        originData: {}, //表单解析默认填充数据
        num: 0, //当前字段序号
        fieldId: 100, //字段id，相当于formEditor的idGlobal,根据id自动生成各字段的名字field101,field102,...
        isDeleteTableField: false, //是否删除数据重构表
        updateTableType: 'normal', //改变表结构类型：normal普通同步、force强制同步
        job: {}, //数据库表的数据结构
        params: {}, //表单信息
        currentLength: '', //当前字段长度
        allNum: 0, //存在已创建字段总数
        formJsonMessage: {}, //表单发布配置
        isReference: 0, //是否已发布、已引用
        isFinish: false, //正在执行完成操作标识
        fullScreen: false, //预览全屏
        tableNum: 0, // 子表单创建字段数
        tableIdList: [],
        childrenTableIdMap: new Map(),
        tempFormObj: {}, // 当前表单的信息
        valiateLength: [], // 存储是否长度超过限制
        delArray:[],//被删除的主表组件数据
        delSubArray:[],//被删除的子表单的组件数据
        delChildData: []  //删除子表单集合
      }
    },
    computed: {
      //多选数据条数
      selectionLength() {
        return this.multipleSelection.length
      }
    },
    mounted() {
      this.getList()  //获取表单数据
      this.getTypes() //获取所有表单分类
    },
    methods: {
        deleteChildData(data){
          this.delChildData = data
        },
        deleteItem(deleteFlag, delItem, tableName){
          if (!delItem || !delItem.isCreated) {
            return
          }
          if (deleteFlag === 'main') {
            this.delArray.push(delItem.__vModel__)
          } else {
            this.delSubArray.push({
              name: delItem.__vModel__,
              tableName
            })
          }
        },
        changeCountFunc (obj) {
            this.changeCount++
            this.formInfo.subFormListData[obj.row].tableName = obj.value
        },
        tableChangeFormat (value, tableIdx, rowIndex) {
            if (value === 'varchar') {
                this.formInfo.subFormListData[tableIdx].fieldData[rowIndex].length = '50'
            } else if (value === 'double' || value === 'decimal') {
                this.formInfo.subFormListData[tableIdx].fieldData[rowIndex].length = '16,2'
            } else {
                this.formInfo.subFormListData[tableIdx].fieldData[rowIndex].length = '0'
            }
        },
      // 每次search框变化则进行筛选,对数据进行逻辑处理
      searchInputChange(value) {
        // 若未输入值，则展示所有数据
        if(null === value || undefined === value){
          this.listRst = this.formTypes;
        } else {
          this.listRst = []; // 结果列表置空
          let regStr =  '';
          // 初始化正则表达式
          for(let i=0; i<value.length; i++){
            regStr = regStr + '(' + value[i] + ')([\\s]*)'; //跨字匹配
          }
          let reg = new RegExp(regStr);
          for(let i=0; i<this.formTypes.length; i++){
            let label = this.formTypes[i].label; //按照名字匹配
            let regMatch = label.match(reg);
            if(null !== regMatch) {// 将匹配的数据放入结果列表中
              this.listRst.push(this.formTypes[i]);
            }
          }
        }
      },
      //获取表单数据
      getList() {
        this.tableLoading = true
        let params = {
          ...this.page,  //页码
          formName: this.searchFormData.name //搜索关键字
        }
        if (this.activeName) { //根据当前选择类别查询
          params.categoryId = this.activeName  //表单类别
        }
        getPageFormInfo(params).then((res) => {
          if (res.code === 0) {
            this.tableData = res.data.list
            this.pageTotal = res.data.total
            this.tableLoading = false
          }
        }).catch(e => {
          console.log('分页获取表单信息:', e)
          this.tableLoading = false
        })
      },
      //获取所有表单类别
      getTypes() {
        getAllCategory().then((res) => {
          if (res.code === 0) {
            this.formTypes = res.data.map((item) => {
              return {
                value: item.id,
                label: item.categoryName
              }
            })
            this.listRst = this.formTypes
          }
        }).catch(e => {
          console.log('获取所有表单分类：', e)
        })
      },
      //获取表单分类数据
      getTypeList() {
        getPageCategory(this.typePage).then((res) => {
          if (res.code === 0) {
            this.formTypeData = res.data.list
            this.typePageTotal = res.data.total
            this.tableTypeLoading = false
          }
        }).catch(e => {
          console.log('分页获取表单分类：', e)
          this.tableTypeLoading = false
        })
      },
      //点击左侧类别，改变表单类型
      changeType(value) {
        this.activeName = value
        this.searchText = ''
        this.page.pageNo = 1
        this.getList() //重新获取表单数据
      },
      //多选rowkey
      getRowKeys(row) {
        return row.id
      },
      //批量删除
      multiDelForm() {
        let reference = [];
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          reference = this.multipleSelection.map((item) => {
            return item.isReference
          })
          if(reference.indexOf(1) !==-1){ //已引用，显示提示
            this.$message({
              showClose: true,
              message: '选中表单已被引用发布，如需删除，请先删除表单发布中该引用表单！',
              type: 'warning',
              duration: 5000
            })
          }else{ //未引用，直接删除
              let ids = this.multipleSelection.map((item) => {
                return item.id
              })
              //根据id删除
              multiDel(ids).then(res => {
                if (res.code === 0) {
                  this.$message.success(res.data)
                  this.$refs.multipleTable.clearSelection()
                  this.page.pageNo = 1
                  this.getList()  //重新获取数据
                }
              }).catch(e=> console.log('批量删除', e ))
            }
        })
      },
      //预览表单
      viewForm() {
        this.formConfData = JSON.parse(this.multipleSelection[0].formJsonUser) //给parser传配置，渲染表单
        this.fullScreen = false //默认不全屏
        this.tableName = this.multipleSelection[0].tableName
        this.dialogPreviewVisible = true //显示表单预览弹窗
      },
      //启用表单
      useForm() {
        enableForm(this.multipleSelection[0].id).then((res) => {
          if (res.code === 0) {
            this.$refs.multipleTable.clearSelection()
            this.getList()
            this.isEnable = 0
            this.$message.success('表单启用成功')
          }
        }).catch(e => console.log('启用表单:', e))
      },
      //禁用表单
      unuseForm() {
        disableForm(this.multipleSelection[0].id).then((res) => {
          if (res.code === 0) {
            this.$refs.multipleTable.clearSelection()
            this.getList()
            this.isEnable = 1
            this.$message.success('表单禁用成功')
          }
        }).catch(e => console.log('禁用表单:', e))
      },
      //历史记录,暂未开发
      historyRecord() {
        this.dialogHistoryVisible = true //显示历史记录弹窗
      },
      //列显隐
      showHide(flag) {
        this.drawer = true  //显示列显隐抽屉
        this.isType = flag //区分是表单还是表单分类
      },
      //多选，数据选择改变
      handleSelectionChange(val) {
        this.multipleSelection = val
        if (val.length === 1) {
          this.isEnable = val[0].isEnable
        }
      },
      //打开表单编辑
      editForm(row) {
        this.delArray = []
        this.delSubArray = []
        this.$refs.design.delChildData = []
        this.isReference = row.isReference  //是否已引用
        if (row.isReference === 1) { //已引用
          this.formJsonMessage = JSON.parse(row.formJsonMessage) //表单发布配置
        }
        this.tableName = row.tableName
        this.formEditData = JSON.parse(row.formJsonData).data  //数据库表的数据结构备份
        if (row.childFormJsonData) {
            this.formEditTableData = JSON.parse(row.childFormJsonData)
        }
        const _this = this
        _this.formEditTableData.forEach(param => {
            const tempData = JSON.parse(param.formJsonData)
            _this.formEditData = [..._this.formEditData, ...tempData]
            const subform = JSON.parse(param.formJsonUser)
            _this.childrenTableIdMap.set(subform.__config__.renderKey, {id: param.id, oldTableName: param.tableName})
        })
        this.allNum = 0 //原始字段计数，用于判断是否有字段被删除
        this.formInfo.id = row.id //表单id
        this.formInfo.basic = {
          formName: row.formName, //表单名
          categoryId: row.categoryId, //表单类别
          formDesc: row.formDesc //表单描述
        }
        this.formName = row.formName
        let json = JSON.parse(row.formJsonUser)
        let {
          fields, //表单组件配置
          fieldId, //组件初始id
          ...config  //表单属性配置
        } = json
        this.fieldId = fieldId  //表单设计新增组件的初始id，避免组件名称重复，出现多个field101,field102...
        // 旧数据添加固定值属性
        if (fields) {
            fields.forEach(comp => {
                if (!this.noShowDefaultList.includes(comp.__config__.tag) && !comp.__config__.defaultSelect) {
                    comp.__config__.defaultSelect = 'staticValue'
                }
            })
            this.$refs.design.drawingList = fields  //给formEditor参数赋值，渲染所有组件
            this.$refs.design.activeData = fields[0] //当前激活组件为第一个组件
        }
        this.num = 0 //存数据到数据库的组件的index标识
        this.updateJsonStatus(this.$refs.design.drawingList) //为字段添加标识
        this.$refs.design.formConf = config //表单属性配置
        this.formInfo.nameData[0].tableName = row.tableName //表名
        // this.formInfo.nameData[0].tableRemark = row.formDesc  //表描述未在数据库中保存，此处显示的为表单描述
        this.formInfo.nameData[0].tableRemark = this.formInfo.basic.formName  // 使用表单名称作为主表的备注
        saveIdGlobal(this.fieldId) //保存组件初始id
        // this.$refs.design.form = {
        //   tableName: row.tableName,
        //   tableRemark: row.formDesc
        // }
        //  this.formInfo.fieldData = JSON.parse(row.formJsonData).data
        this.showDesigner = true //显示表单设计步骤
      },
      //复制表单
      copyForm(row) {
        let formJsonData = JSON.parse(row.formJsonData) //数据结构
        let newName = `${row.tableName}_copy_${this.getRandomStr(3)}`  //随机生成新表名
        this.tempFormObj.tableName = newName
        formJsonData.tableName = newName //替换数据结构里的表名为新表名
        let newFormName = `${row.formName}_copy_${this.getRandomStr(3)}`  //随机生成新表单名
        if (newFormName.length > 200 || newName.length > 64) { //名称超出长度，不复制
        this.$message.error('复制表单的名称长度超过200或表名长度超过64，无法复制')
        } else {
        let params = {
            formName: newFormName, //新表单名
            tableName: newName, //新表名
            // formJsonUser: row.formJsonUser, //表单设计json
            formJsonData: JSON.stringify(formJsonData), //数据结构json
            formDesc: row.formDesc, //表单描述
            categoryId: row.categoryId //表单类别
        }
        let tableCompList = []
        let json = JSON.parse(row.formJsonUser)
        const allFields = json.fields
        tableCompList = allFields.filter(comp => {
            return comp.__config__?.tag === 'Subform'
        })
        let tableJsonData = []
        if (row.childFormJsonData) {
            tableJsonData = JSON.parse(row.childFormJsonData)
        }
        let sysFromVoList = []
        let copyDataList = []
        let curTableNum = 0
        let tempNameList = []
        tableJsonData.forEach((param, index) => {
            const tempName = '_' + this.getRandomStr(3)
            // 更改整体json结构里面的jsonuser
            const curIdx = allFields.findIndex(curItem => {
                return curItem.__vModel__ === param.tableName
            })
            // 更改整体json结构里面的jsonuser
            allFields[curIdx].__vModel__ = param.tableName + '_copy' + tempName
            // 更改childrenData里面的参数tableName
            tableCompList[index].__vModel__ = param.tableName + '_copy' + tempName
            copyDataList.push({
                parentId: '',
                tableName: param.tableName + '_copy' + tempName,
                categoryId: row.categoryId,
                formJsonUser: JSON.stringify(tableCompList[index]),
                formJsonData: param.formJsonData,
                formName: param.tableRemark ? param.tableRemark : param.tableName + '_copy' + tempName
            })
            sysFromVoList.push({
                tableName: param.tableName + '_copy' + tempName,
                tableRemark: param.tableRemark ? param.tableRemark : param.tableName + '_copy' + tempName,
                data: [...JSON.parse(param.formJsonData)],
            })
        })
        // 更改jsonuser里的表名
        json.fields = allFields
        params.formJsonUser = JSON.stringify(json)
        //根据数据结构，创建数据库表
        const _this = this
        createTable(formJsonData).then((res) => {
        if (res.code === 0) {
            //提交表单设计信息
            addFormInfo(params).then(async (res) => {
                if (res.code === 0) {
                    if (tableJsonData.length > 0) {
                        copyDataList.forEach(fieldData => {
                            fieldData.parentId = res.data
                        })
                        await createtablelist(sysFromVoList)
                        savelist(copyDataList).then(async tempRsp => {
                            _this.formInfo.subFormListData = sysFromVoList.map(itemF => {
                                return {
                                    ...itemF,
                                    fieldData: itemF.data
                                }
                            })
                            if (tempRsp.code === 0) {
                                tempRsp.data.forEach((curId, idIndex) => {
                                    _this.formInfo.subFormListData[idIndex].id = curId
                                })
                            }
                            await this.editChildrenJsonData(tableCompList, 'copy', res.data)
                        })
                    }else {
                        this.$message.success('复制表单成功')
                        this.closeDesign()
                        this.page.pageNo = 1
                        this.searchText = ''
                        this.$refs.multipleTable.clearSelection()
                        this.getList()
                    }
                }
            }).catch((e) => {
                console.log('复制表单信息：', e)
            })
        }
        }).catch(e => console.log('创建表：', e))
        }
      },
      //删除表单
      delForm(row) {
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (row.isReference === 1) { //已引用
            this.$message({
              showClose: true,
              message: '该表单已被引用发布，如需删除，请先删除表单发布中该引用表单！',
              type: 'warning',
              duration: 5000
            })
          } else { //未引用
            delFormInfo(row.id).then(res => {
              if (res.code === 0) {
                this.$message.success('删除成功')
                // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
                if (this.page.pageNo > 1 && (this.pageTotal - 1) <= (this.page.pageNo - 1) * this.page
                  .pageSize) {
                  this.page.pageNo--
                }
                this.$refs.multipleTable.clearSelection()
                this.getList()
              }
            }).catch(e => console.log('删除表单信息:', e))
          }
        })
      },
      //打开新增表单设计
      addForm() {
        this.delArray = []
        this.delSubArray = []
        this.$refs.design.delChildData = []
        //表单分类不为空
        if (this.formTypes.length > 0) {
          this.showDesigner = true
          this.formInfo.basic.categoryId = this.activeName  //表单分类默认为当前选中类别
          //给formEditor的表单属性配置赋默认值，避免表单之间影响
          this.$refs.design.formConf = {
            formRef: 'elForm',
            formModel: 'formData',
            size: 'medium',
            labelPosition: 'right',
            labelWidth: 100,
            formRules: 'rules',
            gutter: 15,
            disabled: false,
            span: 24,
            formBtns: true,
            btnConfig: [{ label: '确定', text: '提交', click: 'submit', checked: true, type: 'default' }, { label: '重置', text: '重置', click: 'reset', checked: true, type: 'default' }, { label: '保存', text: '保存', click: 'save', checked: true, type: 'default' }, { label: '取消', text: '取消', click: 'cancel', checked: true, type: 'default' }],
            btnPosition: 'center',
            ruleConfig: [],
            formType:'page',
            dialogWidth: 1000,
            dialogTop:0,
            labelDescriptionPosition:'button'
          }
        } else { //表单分类为空
          this.$message({
            showClose: true,
            message: '请先通过分类管理添加表单分类',
            type: 'warning',
            duration: 4000
          })
        }
      },

      //同步数据库取消按钮
      cancelTableConstructor(){
        // this.addFields = []
        // this.formInfo.fieldData = []
        // this.num = 0
        // this.getAllFields(this.$refs.design.drawingList) //根据表单组件自动生成数据库表结构
        // this.stepNum = 2;
        // setTimeout(()=>{
        //   this.isDeleteTableField =false
        //   this.alterData =[]
        //   this.stepNum = 3;
        // },50)
        this.alterData =[]
        this.alterTableDataMap = new Map()
        this.dialogConstructorVisible = false;
        this.tableLoading = false   //取消loading
        // this.isFinish=false
      },
      //修改表单，更改表结构
      updateTableConstructor() {
        this.dialogConstructorVisible = false
        console.log('addMap:', this.addTableFieldsMap)
        console.log('editMap:', this.alterTableDataMap)
        if (this.updateTableType === 'normal') { //普通同步，保留原表

          if (this.alterData.length > 0 || this.formInfo.nameData[0].tableName !== this.tableName) {  //修改字段或修改表名
            //修改主表字段表名
            alterTable({
              data: this.alterData, //修改字段
              tableNameNew: this.formInfo.nameData[0].tableName, //新表名
              tableNameOld: this.tableName //旧表名
            }).then((res) => {
              if (res.code === 0) {
                // if (this.addFields.length > 0) { //有新增字段
                //   this.addNewField() //在数据库表中添加字段
                // } else {
                //   this.editFormInfos() //修改表单信息
                // }
                this.editFormInfos() //修改表单信息
              }
            }).catch(e => console.log(e))
          }

            //更新子表单数据库表
            if (this.alterTableDataMap.size > 0 || this.changeCount > 0) {
            this.alterTableDataMap.forEach((valueList, onlyKey) => {
                const editList = valueList.filter(cc => {
                    return cc.newName || cc?.oldName !== cc.name
                })
                const editData = {
                  data: editList, //修改字段
                  tableNameNew: onlyKey, //新表名
                  tableNameOld: this.childrenTableIdMap.get(valueList[0].renderKey)?.oldTableName || '' //旧表名
                }
                alterTable(editData)
            })
            // 更新结构
            this.editChildTableRelation()
            // 更新表单全部信息(包括子表单)
            this.editFormInfos()
          }


          if(this.$refs.design.delDrawing?.length > 0){ //点击了清空所有组件
            const childDelList = [] //子表单数据
            let masterDelList = [] //主表删除字段
            const masterDelArray = [] //主表所有信息
            this.$refs.design.delDrawing.map((item) => {
              if(item.__config__.tag === 'Subform'){ //子表单
                childDelList.push(item.__vModel__)
              }else{
                masterDelList.push(item.__vModel__)
              }
            })
            this.$refs.design.delDrawing = [] // 清空存的 全部清空数据
            const addFields = JSON.parse(JSON.stringify(this.addFields))
            const addtableName = this.formInfo.nameData[0]?.tableName
            if(masterDelList.length > 0){ //删除主表
              if(this.delArray.length > 0){// 表示手动删除了一个组件之后 在清空了
                masterDelList = [...masterDelList,...this.delArray]
              }
              masterDelArray.push({
                  tableName: this.formInfo.nameData[0].tableName, //表名
                  fieldNameList: masterDelList //删除的字段
              })
                //在表中删除字段
              deleteField(masterDelArray).then(res => {
                this.delArray =[]
                    // 主表新增字段
                if (addFields.length > 0) { //添加字段
                    let newJob = {
                      tableName: addtableName, //表名
                      data: addFields //添加的字段
                    }
                    //在表中添加字段
                    addField(newJob).then(res => {
                      if (res.code === 0) {
                        this.editFormInfos() //修改表单信息
                      }
                    }).catch(e => console.log('添加表字段：', e))
                }
              }).catch(e => console.log('删除表字段：', e))
            }
            if(childDelList.length > 0){ //子表单删除
              deleteAllField(childDelList)
            }
              // 子表单存在新增的数据情况处理
              if (this.addTableFieldsMap.size > 0) {
                // 新增子表单字段数据
                let needCreateList = []
                this.addTableFieldsMap.forEach((valueList, onlyKey) => {
                    const newData = []
                    let newAddObj = {
                        data: [],
                        tableName: ''
                    }
                    valueList.forEach(curTemp => {
                        const id = this.childrenTableIdMap.get(curTemp.renderKey)?.id
                        if (id) {
                            let addData = {
                                tableName: onlyKey, //表名
                                data: [curTemp] //添加的字段
                            }
                            //在表中添加字段
                            addField(addData)
                        } else {
                            newData.push(curTemp)
                        }
                    })
                    // 如果存在新增子表单，则进行新建子表逻辑
                    if (newData.length > 0) {
                        newAddObj.data = [...newData]
                        newAddObj.tableName = onlyKey
                        newAddObj.isRestructure = "1"
                        needCreateList.push(newAddObj)
                    }
                })
                // 如果存在新增的子表单，则进行创建tablelist逻辑
                needCreateList.length > 0 && createtablelist(needCreateList)
                // 更新结构
                this.editChildTableRelation()
                // 更新表单全部信息(包括子表单)
                this.editFormInfos()
              }

          }else{
            if (this.delArray.length > 0 || this.delSubArray.length > 0){ // 主表删除字段  子表单删除字段
              const tempDelArray = []
              // 主表删除字段
              if (this.delArray.length > 0) {
                tempDelArray.push({
                  tableName: this.formInfo.nameData[0].tableName, //表名
                  fieldNameList: this.delArray //删除的字段
                })
              }
              // 子表单删除字段
              if (this.delSubArray.length > 0) {
                for (let i = 0; i < this.delSubArray.length; i++) {
                  const element = this.delSubArray[i];
                  const { tableName, name } = element
                  const tableNameIndex = tempDelArray.findIndex((item) => item.tableName === tableName)
                  if (tableNameIndex !== -1) {
                    tempDelArray[tableNameIndex].fieldNameList.push(name)
                  } else {
                    tempDelArray.push({
                      tableName,
                      fieldNameList: [name]
                    })
                  }
                }
              }
              const addFields = JSON.parse(JSON.stringify(this.addFields))
              const addtableName = this.formInfo.nameData[0]?.tableName
              const addTableFieldsMap = this.addTableFieldsMap
              if (tempDelArray.length > 0) {
                deleteField(tempDelArray).then(res => {//在数据库表中删除字段
                  // 主表新增字段
                if (addFields.length > 0) { //添加字段
                     //在数据库表中添加字段
                    let newJob = {
                      tableName: addtableName, //表名
                      data: addFields //添加的字段
                    }

                    //在表中添加字段
                    addField(newJob).then(res => {
                      if (res.code === 0) {
                        this.editFormInfos() //修改表单信息
                      }
                    }).catch(e => console.log('添加表字段：', e))

                }
                // 子表单存在新增的数据情况处理
                if (addTableFieldsMap.size > 0) {
                  // 新增子表单字段数据
                  let needCreateList = []
                  addTableFieldsMap.forEach((valueList, onlyKey) => {
                      const newData = []
                      let newAddObj = {
                          data: [],
                          tableName: ''
                      }
                      valueList.forEach(curTemp => {
                          const id = this.childrenTableIdMap.get(curTemp.renderKey)?.id
                          if (id) {
                              let addData = {
                                  tableName: onlyKey, //表名
                                  data: [curTemp] //添加的字段
                              }
                              //在表中添加字段
                              addField(addData)
                          } else {
                              newData.push(curTemp)
                          }
                      })
                      // 如果存在新增子表单，则进行新建子表逻辑
                      if (newData.length > 0) {
                          newAddObj.data = [...newData]
                          newAddObj.tableName = onlyKey
                          newAddObj.isRestructure = "1"
                          needCreateList.push(newAddObj)
                      }
                  })
                  // 如果存在新增的子表单，则进行创建tablelist逻辑
                  needCreateList.length > 0 && createtablelist(needCreateList)
                  // 更新结构
                  this.editChildTableRelation()
                  // 更新表单全部信息(包括子表单)
                  this.editFormInfos()
                }
              }).catch(e => console.log('删除表字段：', e))
                // 更新结构
                this.editChildTableRelation()
                // 更新表单全部信息(包括子表单)
                this.editFormInfos()
              }

            }else{ //只新增
                 // 主表新增字段
              if (this.addFields.length > 0) { //添加字段
                  this.addNewField() //在数据库表中添加字段
              }
              // 子表单存在新增的数据情况处理
              if (this.addTableFieldsMap.size > 0) {
                // 新增子表单字段数据
                let needCreateList = []
                this.addTableFieldsMap.forEach((valueList, onlyKey) => {
                    const newData = []
                    let newAddObj = {
                        data: [],
                        tableName: ''
                    }
                    valueList.forEach(curTemp => {
                        const id = this.childrenTableIdMap.get(curTemp.renderKey)?.id
                        if (id) {
                            let addData = {
                                tableName: onlyKey, //表名
                                data: [curTemp] //添加的字段
                            }
                            //在表中添加字段
                            addField(addData)
                        } else {
                            newData.push(curTemp)
                        }
                    })
                    // 如果存在新增子表单，则进行新建子表逻辑
                    if (newData.length > 0) {
                        newAddObj.data = [...newData]
                        newAddObj.tableName = onlyKey
                        newAddObj.isRestructure = "1"
                        needCreateList.push(newAddObj)
                    }
                })
                // 如果存在新增的子表单，则进行创建tablelist逻辑
                needCreateList.length > 0 && createtablelist(needCreateList)
                // 更新结构
                this.editChildTableRelation()
                // 更新表单全部信息(包括子表单)
                this.editFormInfos()
              }
            }
          }

        } else if (this.updateTableType === 'force') { //强制同步，删除原表，创建新表
          this.createNewDataTable('1','force')
        }
      },
      // 冒泡校验重复项
      loopValidateName (list, strFlag, num) {
        for (let x = 0; x < list.length - 1; x++) {
            const firstName = list[x].name
            for (let y = x + 1; y < list.length; y++) {
                const secondName = list[y].name
                if (firstName === secondName) {
                    this.$message.error(strFlag === 'primary' ?
                        `主表第 ${x + 1} 个字段与第 ${y + 1} 个字段 ${firstName} 重复` :
                        `第${num + 1}个子表单的第 ${x + 1} 个与第 ${y + 1} 个字段 ${firstName} 重复`)
                    return firstName
                }
            }
        }
      },
      //表单设计完成，提交数据，生成数据库表   新增/修改
      finishForm() {
        // 判断最大长度，不能超过数据库最大长度限制
        let numForm = 0
        let numSubForm = 0
        //varchar类型不能超过20个  ---组件数量校验
        //1、正常组件
        if(this.formInfo.fieldData.length > 0){
          this.formInfo.fieldData.map((item,index)=>{
            if(item.format === 'varchar'){
              numForm = numForm + parseInt(item.length)
            }
          })
        }
        if(this.delChildData.length > 0){  // 编辑有修改子表单
          deleteAllField(this.delChildData)
        }
        if(numForm>16000){
          this.$message.error(`${this.formInfo.nameData[0].tableName}中字符总长度不能大于数据库最大长度限制，可将文本类型改为长文本类型`)
          return
        }
        if(this.formInfo.subFormListData.length > 0) {
          //2、子表单中组件
          for(let i=0;i<this.formInfo.subFormListData.length;i++){
            numSubForm = 0
            for(let j=0;j<this.formInfo.subFormListData[i].fieldData.length;j++){
              if(this.formInfo.subFormListData[i].fieldData[j].format === 'varchar'){
                numSubForm = numSubForm + parseInt(this.formInfo.subFormListData[i].fieldData[j].length)
              }
              if(numSubForm>16000){
                this.$message.error(`${this.formInfo.subFormListData[i].tableName}中字符总长度不能大于数据库最大长度限制，可将文本类型改为长文本类型`)
                return
              }
            }
          }
        }
        // 主表-主表 字段名重复
        let primaryNames = this.loopValidateName(this.formInfo.fieldData, 'primary')
        if (primaryNames) {
            return
        }
        // 单个子表内 字段名重复
        if (this.formInfo.subFormListData.length > 0) {
            for (let z = 0; z < this.formInfo.subFormListData.length; z++) {
                const curSub = this.formInfo.subFormListData[z]
                for (let a = 0; a < curSub.fieldData.length; a++) {
                    let tableNames = this.loopValidateName(curSub.fieldData, 'children', z)
                    if (tableNames) {
                        return
                    }
                    const curLineName = curSub.fieldData[a].name
                    const flag = this.formInfo.fieldData.some(cc => {
                        return cc.name === curLineName
                    })
                    // 主表-子表 字段名重复
                    if (flag) {
                        this.$message.error(`第 ${z+1} 个子表单的字段名 ${curLineName} 与主表字段名重复`)
                        return
                    }
                }
            }
            let valiateFlag = false
            // 当前子表 与 另一子表 的字段校验
            for (let m = 0; m < this.formInfo.subFormListData.length - 1; m++) {
                for (let n = m + 1; n < this.formInfo.subFormListData.length; n++) {
                    const firstFieldList = this.formInfo.subFormListData[m].fieldData
                    const secondFieldList = this.formInfo.subFormListData[n].fieldData
                    firstFieldList.forEach((first, indexone) => {
                        const { name } = first
                        secondFieldList.forEach((second, indextwo) => {
                            if (name === second.name) {
                                valiateFlag = true
                                this.$message.error(`第 ${m+1} 个子表单与第${n+1}个子表单 ${name} 的字段名重复`)
                                return
                            }
                        })
                    })
                }
            }
            // 拿到子表单的所有表名
            const allnames = this.formInfo.subFormListData.map(objField => {
                return objField.tableName
            })
            // 判断主表表名是否存在于子表单所有名称中
            const flag = allnames.some(curname => {
                return this.formInfo.nameData[0].tableName === curname
            })
            // 去重，然后校验长度来判断是否子表单名称相互是否重复(写两种是为了区分提示)
            const newNamesList = Array.from(new Set(allnames))
            if (flag) {
                valiateFlag = true
                this.$message.error(`主表表名 与 子表单名称 重复，请重新输入`)
            }
            if (newNamesList.length !== this.formInfo.subFormListData.length) {
                valiateFlag = true
                this.$message.error(`当前表单内 子表单名称 存在重复，请重新输入`)
            }
            if (valiateFlag) {
                return
            }
        }
        // 此处赋值是为了避免部分接口调用完页面刷新，formInfo对象被清空后续接口无法使用表单id
        this.tempFormObj = {
            id: this.formInfo.id,
            tableName: this.formInfo.nameData[0].tableName
        };
        this.$refs["tableInfo"].validate((valid) => {
            if (valid) {
                if (this.formInfo.subFormListData.length > 0) {
                    let rightCount = 0
                    const _this = this
                    _this.formInfo.subFormListData.forEach((compField, index) => {
                        // 循环校验子表的数据
                        _this.$refs['childTableInfo' + index][0].$refs['childTableInfo'].validate(async(childValidate) => {
                            if (childValidate) {
                                rightCount++
                            }
                            if (rightCount === _this.formInfo.subFormListData.length) {
                                _this.saveAssemble()
                            }
                        });
                    })
                } else {
                    this.saveAssemble()
                }
            } else {
                const restFieldData = this.formInfo.fieldData.slice((this.configPage.pageNo-1)*this.configPage.pageSize,this.configPage.pageNo*this.configPage.pageSize)
                for (let index = 0; index < restFieldData.length; index++) {
                    const element = restFieldData[index];
                    const { name } = element
                    // let pattern = /^[a-zA-Z][^\u4e00-\u9fa5]+$/
                    let pattern = /^[a-z][^\u4e00-\u9fa5A-Z ]+$/
                    if (!pattern.test(name)) {
                        this.$message.error(`当前页第${index %this.configPage.pageSize +1}个参数有误，请输入符合要求的字段名`)
                    } else if (name.length > 64){
                        this.$message.error(`当前页第${index %this.configPage.pageSize +1}个参数，长度不能超过64`)
                    }
                }
            }
        });
      },
      // 合并代码
      saveAssemble () {
        if (this.formInfo.fieldData?.length > this.configPage.pageSize) {
            const restFieldData = this.formInfo.fieldData.filter((_, index) =>{
            return (this.configPage.pageNo-1)*this.configPage.pageSize+1 <= index < this.configPage.pageNo*this.configPage.pageSize
            })
            for (let index = 0; index < restFieldData.length; index++) {
            const element = restFieldData[index];
            const { name } = element
            // let pattern = /^[a-zA-Z][^\u4e00-\u9fa5]+$/
            let pattern = /^[a-z][^\u4e00-\u9fa5A-Z ]+$/
            if (!pattern.test(name)) {
                this.$message.error(`第${parseInt(index/this.configPage.pageSize+1)}页 第${index %this.configPage.pageSize +1}个参数有误，请输入符合要求的字段名`)
                return false
            } else if (name.length > 64){
                this.$message.error(`第${parseInt(index/this.configPage.pageSize+1)}页 第${index %this.configPage.pageSize +1}个参数，长度不能超过64`)
                return false
            } else {
                let names = this.formInfo.fieldData.filter((item) => {
                return item.name === name
                })
                if (names.length > 1) {
                this.$message.error(`第${parseInt(index/this.configPage.pageSize+1)}页 第${index %this.configPage.pageSize +1}个参数，${name}字段名重复`)
                return false
                }
            }
            }
        }
        this.tableLoading = true
        this.num = 0
        this.tableNum = 0
        this.formInfo.formJsonUser.fieldId = this.fieldId //保存当前组件的最大id,下次编辑时以此为基准自动生成组件名
        //数据库表的数据结构
        this.job = {
            tableName: this.formInfo.nameData[0].tableName, //表名
            data: this.formInfo.fieldData //字段
        }
        // 更新jsonuser里面子表单的字段名
        if (this.formInfo.subFormListData.length > 0) {
            let curTableNum = 0
            this.$refs.design.drawingList.forEach(comp => {
                if (comp.__config__?.tag === 'Subform') {
                    const newName = this.formInfo.subFormListData[curTableNum].tableName
                    const oldName = comp.__vModel__
                    if (oldName !== newName) { // 新旧名称不一样存在两种情况(已有表名进行更改；新增表名进行更改)
                        // 如果能查出来旧名称，说明是更新的数据
                        const oldTableName = this.childrenTableIdMap.get(comp.__config__.renderKey)?.oldTableName
                        if (oldTableName) {
                            this.formInfo.subFormListData[curTableNum].fieldData.forEach(editField => {
                                editField.renderKey = comp.__config__.renderKey
                            })
                            this.alterTableDataMap.set(newName, this.formInfo.subFormListData[curTableNum].fieldData)
                        }
                        comp.__vModel__ = this.formInfo.subFormListData[curTableNum].tableName
                    }
                    comp.__config__.children[0].__config__.children.forEach((fieldComp, idx) => {
                        // 更新字段名称
                        fieldComp.__vModel__ = this.formInfo.subFormListData[curTableNum].fieldData[idx].name
                    })
                    curTableNum++
                }
            })
        }
        this.formInfo.formJsonUser.fields = [...this.$refs.design.drawingList]
        this.updateJsonRule(this.formInfo.formJsonUser.fields) //更新表单校验规则，给组件添加默认校验规则
        // 校验数据库长度与最大输入字符长度
        this.validateAllLength()
        if (this.valiateLength.length > 0) {
            this.tableLoading = false
            return
        }
        //表单信息
        this.params = {
            ...this.formInfo.basic, //表单基本信息，表单名、表单分类、表单描述
            tableName: this.formInfo.nameData[0].tableName, //表名
            formJsonUser: JSON.stringify(this.formInfo.formJsonUser), //表单设计json
            formJsonData: JSON.stringify(this.job) //数据库表的数据结构json
        }
        const _this = this
        if (this.formInfo.id) { //编辑修改表单'
            // if (this.allNum < this.formEditData.length) {  //字段数少于原始字段数
            // this.isDeleteTableField = true //需删除数据重构表
            // }
            if(this.isDeleteTableField) { //删除了字段，表结构改变，需删除数据重构表
                if (this.isReference === 0) { //未发布，直接强制同步表结构
                this.createNewDataTable('1', 'force') //删除原表，创建新表
                } else { //已发布，提示
                this.$confirm('已修改字段类型或删除字段，是否确定强制同步表结构', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.createNewDataTable('1', 'force')
                }).catch(
                    ()=>{
                    this.addFields = []
                    this.alterData =[]
                    this.tableLoading = false
                    this.formInfo.fieldData = []
                    this.formInfo.subFormListData = []
                    this.num = 0
                    this.getAllFields(this.$refs.design.drawingList) //根据表单组件自动生成数据库表结构
                    this.isDeleteTableField =false
                    this.addTableFieldsMap = new Map()
                    this.alterTableDataMap = new Map()
                    this.isFinish = false
                    }
                )
                }
            } else if (_this.alterData.length > 0 || _this.addFields.length > 0 || _this.formInfo.nameData[0].tableName !== _this.tableName
            || _this.addTableFieldsMap.size > 0 || _this.alterTableDataMap.size > 0 || _this.changeCount > 0 || _this.delArray.length>0 || _this.delSubArray.length>0) { //修改字段名、长度、描述,添加字段，修改表名
                if (_this.isReference === 0) { //未发布
                    this.updateTableType = 'force'
                    this.updateTableConstructor()  //直接强制同步
                } else { //已发布，需选择如何同步
                    this.updateTableType = 'normal'
                    this.dialogConstructorVisible = true //显示弹窗，选择普通同步、强制同步
                }
            } else {
                this.editListFormInfos() // 修改子表单的信息
                this.editFormInfos() //修改表单信息
            }
        } else { //新增表单
            this.createNewDataTable()  //创建数据库表
            return true
        }
      },
      editListFormInfos () {
        if (this.formInfo.subFormListData.length > 0) {
            let tableCompList = []
            tableCompList = this.$refs.design.drawingList.filter(comp => {
                return comp.__config__?.tag === 'Subform'
            })
            const newList = []
            this.formInfo.subFormListData.forEach((item, index) => {
                let tempObj = {}
                const id = this.childrenTableIdMap.get(item.renderKey)?.id
                if (id) {
                    item.id = id
                    tempObj = {
                        id: id,
                        tableName: item.tableName,
                        formJsonUser: JSON.stringify(tableCompList[index]),
                        formJsonData: JSON.stringify(item.fieldData)
                    }
                    newList.push(tempObj)
                }
            })
            // 更新子表单的jsonuser
            editlist(newList)
        }
      },
      validateAllLength () {
        const list = [...this.formInfo.formJsonUser.fields]
        const _this = this
        _this.valiateLength = []
        for (let a = 0; a < this.formInfo.fieldData.length; a++) {
            const curField = this.formInfo.fieldData[a]
            const comp = this.loopFindComp(curField.name, list)
            if (comp && ['input', 'textarea', 'password'].includes(comp.__config__.tagIcon)) {
                if (comp['show-word-limit'] && ((comp.maxlength??'') !== '' &&  Number(curField.length) < Number(comp.maxlength))) {
                    _this.$message.error(curField.name + ' 字段不得小于限制输入字符长度')
                    _this.valiateLength.push(false)
                    return false
                }
            }
        }
        for (let b = 0; b < _this.formInfo.subFormListData.length; b++) {
            const curRow = _this.formInfo.subFormListData[b]
            for (let c = 0; c < curRow.fieldData.length; c++) {
                const row = curRow.fieldData[c]
                const comp = this.loopFindComp(row.name, list)
                if (comp && ['input', 'textarea', 'password'].includes(comp.__config__.tagIcon)) {
                    if (comp['show-word-limit'] && ((comp.maxlength??'') !== '' &&  Number(row.length) < Number(comp.maxlength))) {
                        _this.$message.error(row.name + ' 字段不得小于限制输入字符长度')
                        _this.valiateLength.push(false)
                        return false
                    }
                }
            }
        }
      },
      loopFindComp (curField, list) {
        for (let i = 0; i < list.length; i++) {
            let item = list[i]
            if (['el-card','el-tabs','Steps','el-collapse'].includes(item.__config__.tag)) {
                //布局组件，遍历内部子组件
                item.__config__.children.forEach((c) => {
                    this.loopFindComp(curField, c.__config__.children)
                })
            } else if (item.__config__.tag === 'Subform') {
                const tableCompList = item.__config__.children[0].__config__.children
                for (let x =0; x < tableCompList.length; x++) {
                    if (curField === tableCompList[x].__vModel__) {
                        return tableCompList[x]
                    }
                }
            } else {
                if (curField === item.__vModel__) {
                    return item
                }
            }
        }
      },
      // 强制子表单关系重构
      editChildTableRelation () {
        let tableCompList = []
        let curCount = 0
        if (this.formInfo.subFormListData.length > 0) {
            tableCompList = this.$refs.design.drawingList.filter(comp => {
                return comp.__config__?.tag === 'Subform'
            })
        } else {
            this.editChildrenJsonData([], 'edit', this.tempFormObj.id);
        }
        this.formInfo.subFormListData.forEach((item, index) => {
            let tempObj = {}
            const id = this.childrenTableIdMap.get(item.renderKey)?.id
            if (id) {
                item.id = id
                tempObj = {
                    id: id,
                    tableName: item.tableName,
                    categoryId: this.formInfo.basic.categoryId,
                    formJsonUser: JSON.stringify(tableCompList[index]),
                    formJsonData: JSON.stringify(item.fieldData)
                }
                //如果是编辑的子表单，则更新子表单的关系
                editFormInfo(tempObj).then((res) => {
                    if (res.code === 0) {
                        curCount++
                        if (curCount === this.formInfo.subFormListData.length) {
                            this.editChildrenJsonData(tableCompList, 'edit', this.tempFormObj.id);
                        }
                    }
                }).catch(e => { console.error(e) })
            } else {
                tempObj = {
                    parentId: this.formInfo.id,
                    tableName: item.tableName,
                    formName: item.tableRemark,
                    categoryId: this.formInfo.basic.categoryId,
                    formJsonUser: JSON.stringify(tableCompList[index]),
                    formJsonData: JSON.stringify(item.fieldData)
                }
                // 如果是新增的子表单，则需要先创建关系
                savelist([tempObj]).then((res) => {
                    if (res.code === 0) {
                        curCount++
                        item.id = res.data[0]
                        if (curCount === this.formInfo.subFormListData.length) {
                            this.editChildrenJsonData(tableCompList, 'edit', this.tempFormObj.id);
                        }
                    }
                }).catch(e => { console.error(e) })
            }
        })
      },
      //创建数据库表
      createNewDataTable(flag, reset) {
        // this.params.formJsonData = JSON.stringify(this.job)
        let addTableVoList = []
        let jobTwo = []
        let tableCompList = []
        let sysFromVoList = []
        if (this.formInfo.subFormListData.length > 0) {
            tableCompList = this.$refs.design.drawingList.filter(comp => {
                return comp.__config__?.tag === 'Subform'
            })
        }
        const _this = this
        _this.formInfo.subFormListData.forEach((item, index) => {
            const oldTableName = _this.childrenTableIdMap.get(item.renderKey)?.oldTableName
            if (oldTableName && oldTableName !== item.tableName && reset !== 'force') {
                // 子表单表名被修改，需更新子表表名数据
                alterTable({
                    data: [...item.fieldData],
                    tableNameNew: item.tableName,
                    tableNameOld: oldTableName
                })
            }
            if (!oldTableName) {
                // 新增的子表数据
                addTableVoList.push({
                    tableName: item.tableName,
                    tableRemark: item.tableRemark,
                    data: [...item.fieldData],
                })
            }
            sysFromVoList.push({
                tableName: item.tableName,
                tableNameOld: oldTableName,
                isRestructure: "1",
                tableRemark: item.tableRemark,
                data: [...item.fieldData],
            })
        })
        if (flag === '1') { //删除数据重构表
            this.job.isRestructure = flag  //重构表的标识
            addTableVoList.forEach(vo => {
                vo.isRestructure = flag
            })
            // 强制更新表
            if(reset==='force'){
                //创建表
                this.job.tableNameOld = this.tableName //旧表名
                createTable(this.job).then((res) => {
                if (res.code === 0) {
                    if (this.formInfo.subFormListData.length > 0) {
                        createtablelist(sysFromVoList)
                    }
                    this.editChildTableRelation()
                    this.editFormInfos() //修改表单数据
                }
                }).catch(e => console.log('创建表：', e))
            } else {
                // 普通更新
                let params  = {
                tableName: this.formInfo.nameData[0].tableName, //表名
                data: this.alterData //修改字段
                }
                updatatablecolumn(params).then((res) => {
                if (res.code === 0) {
                    if (this.formInfo.subFormListData.length > 0) {
                        addTableVoList.length > 0 && createtablelist(addTableVoList)
                    }
                    this.editChildTableRelation()
                    this.editFormInfos() //修改表单数据
                }
                }).catch(e => console.log('更新表：', e))
            }
        } else {
            // 新创建的表单
            const _that = this
            createTable(this.job).then((res) => {
                if (res.code === 0) {
                //提交表单数据
                addFormInfo(_that.params).then((resp) => {
                    if (res.code === 0) {
                        const sysFromVoList = []
                        jobTwo = []
                        _that.formInfo.subFormListData.forEach((item, index) => {
                            sysFromVoList.push({
                                tableName: item.tableName,
                                tableRemark: item.tableRemark,
                                parentId: resp.data,
                                data: [...item.fieldData]
                            })
                            jobTwo.push({
                                tableName: item.tableName,
                                formName: item.tableRemark,
                                categoryId: this.formInfo.basic.categoryId,
                                parentId: resp.data,
                                formJsonUser: JSON.stringify(tableCompList[index]),
                                formJsonData: JSON.stringify(item.fieldData)
                            })
                        })
                        if (_that.formInfo.subFormListData.length > 0) {
                            createtablelist(sysFromVoList)
                            savelist(jobTwo).then(tempRsp => {
                                if (tempRsp.code === 0) {
                                    tempRsp.data.forEach((curId, idIndex) => {
                                        _that.formInfo.subFormListData[idIndex].id = curId
                                    })
                                    _that.editChildrenJsonData(tableCompList, 'add', resp.data);
                                }
                            })
                        } else {
                            this.$message.success('新增表单成功')
                            this.closeDesign()
                            this.page.pageNo = 1
                            this.searchText = ''
                            this.$refs.multipleTable.clearSelection()
                            this.getList()
                        }
                    }
                }).catch((e) => {
                    console.log('新增表单信息：', e)
                })
                }
            }).catch(e => console.log('创建表：', e))
        }
      },
      // 更新主表childrenJsonData，不然子表单字段数据对不上
      editChildrenJsonData (onlyTableCompList, flag, formId) {
        const allChildrenTableCompList = []
        let curTableNum = 0
        onlyTableCompList.forEach((comp, curIndx) => {
            allChildrenTableCompList.push({
                tableName: this.formInfo.subFormListData[curTableNum].tableName,
                id: this.formInfo.subFormListData[curTableNum].id,
                formJsonData: JSON.stringify(this.formInfo.subFormListData[curTableNum].fieldData),
                formJsonUser: JSON.stringify(comp),
            })
            curTableNum++
        })
        console.log('allChildrenTableCompList', allChildrenTableCompList)
        // 更新主表包含的childFormJsonData
        editFormInfo({
            id: formId,
            tableName: this.tempFormObj.tableName,
            childFormJsonData: JSON.stringify(allChildrenTableCompList)
        }).then((rsp) => {
            if (rsp.code === 0) {
                 this.$message.success((flag === 'edit' ? '修改' : flag === 'add' ? '新增' : '复制') + '表单成功')
                this.closeDesign()
                this.page.pageNo = 1
                this.searchText = ''
                this.$refs.multipleTable.clearSelection()
                this.getList()
            }
        }).catch(e => { console.error(e) })
      },
      //数据库表添加新字段
      addNewField() {
        let newJob = {
          tableName: this.formInfo.nameData[0].tableName, //表名
          data: this.addFields //添加的字段
        }
        //在表中添加字段
        addField(newJob).then(res => {
          if (res.code === 0) {
            this.editFormInfos() //修改表单信息
          }
        }).catch(e => console.log('添加表字段：', e))
      },
      // 数据库表删除子表单新字段
      delField(data) {
        //在表中删除字段
        deleteField(data).then(res => {
          this.delArray =[]
          this.delSubArray = []
        }).catch(e => console.log('删除表字段：', e))
      },
      //修改表单所有基本信息(包括子表单的结构)
      editFormInfos() {
        if(!!this.formInfo.id){  //避免出现id为''
          this.params.id = this.formInfo.id //当前表单id
          if (this.isReference === 1) { //已发布
            if (this.allNum < this.formEditData.length || this.delArray.length > 0 || this.delSubArray.length > 0) { //字段数少于原始字段数
              this.formEditData.map((item) => {
                if (!item.isExist) { //不存在，已删除该字段
                  this.updateJsonMessageDel(item.name) //表单发布json中同步删除对应字段的信息
                }
              })
            }
            if (this.addFields.length > 0 || this.addTableFieldsMap.size > 0) {  //已添加新字段
              this.updateJsonMessageAdd()  //表单发布json中同步添加对应字段的信息
            }
            this.params.formJsonMessage = JSON.stringify(this.formJsonMessage) //同步后的最新的表单发布配置json
          }

          //修改表单信息
          editFormInfo(this.params).then((res) => {
            if (res.code === 0) {
              this.$message.success('修改表单成功')
              this.closeDesign()
              this.getList()
            }
          }).catch((e) => {
            console.log('编辑表单信息：', e)
          })
        }
      },
      //关闭表单设计,重置、清空、赋默认值
      closeDesign() {
        this.showDesigner = false
        this.tableLoading = false
        this.stepNum = 1
        this.formInfo.id = ''
        this.fieldId = 100 //重置组件id
        saveIdGlobal(this.fieldId) //保存组件id
        this.formName = '' //表单名清空
        this.formEditData = [] //编辑备份数据清空
        this.isReference = 0
        this.isDeleteTableField = false
        this.addFields = [] //新增字段清空
        this.alterData = [] //修改字段清空
        this.addTableFieldsMap = new Map()
        this.alterTableDataMap = new Map()
        this.$refs.basicForm.resetFields() //重置第一步的表单
        // this.$refs.datasource.resetFields()
        this.$refs.design.drawingList = [] //表单设计器组件列表清空
        this.formInfo.nameData[0].tableName = ''
        this.formInfo.nameData[0].tableRemark = ''
        this.job = {} //清空数据库表的数据结构
        this.params = {} //清空表单信息
        // this.isFinish = false //表单设计保存完成，修改标识
        // this.$refs.design.form.tableName = ''
        // this.$refs.design.form.tableRemark = ''
      },
      //根据组件类型返回字段默认长度和默认数据格式
      //type：组件类型, typeIcon:组件图标, precision:小数精度,format:日期格式化形式
      getTypeDefault(com,type, typeIcon, percision, format) {
        if (textTypes.includes(type)) { //文本类型
          if (['el-upload','tinymce','signature',''].includes(type)) { //上传组件、富文本
            return {
              length: '0',
              format: 'longtext'
            }
          }else if (type === 'el-input') {
            //单行文本、多行文本、密码、编码---el-input
            if(com['show-word-limit']){
              return {
                length: com.maxlength,
                format: 'varchar'
              }
            }else if(com.type === 'textarea') {  // 多行文本  -- 格式类型 长文本
              return {
                length: '0',
                format: 'longtext'
              }
            }else{
              return {
                  length: '100',
                  format: 'varchar'
                }
            }
          } else if(type === 'el-time-picker' && typeIcon === 'time') { // 时间选择
             return {
              length: '0',
              format: 'time'
            }
          } else if(type === 'el-date-picker' && typeIcon === 'date') { // 日期选择
             return {
              length: '0',
              format: 'datetime'
            }
          } else if (typeIcon === 'date-range' || typeIcon === 'time-range') {  //日期范围  时间范围 是文本格式
            return {
              length: '100',
              format: 'varchar',
            }
          }else if (noRules.includes(typeIcon) || ['getMapPoint'].includes(type)) {
            //返回数组的组件、地图选点组件
            return {
              length: '100',
              format: 'varchar'
            }
          } else {
            return {
              length: '50',
              format: 'varchar'
            }
          }
        } else if (intTypes.includes(type)) { //数字类型
          if(com.__config__.decimalPlaces > 0){
            // 小数类型
            return {
              length: `16,${com.__config__.decimalPlaces}`,
              format: 'decimal'
            }
          }else if(percision !== undefined) {
            // 小数类型
            return {
              length: `16,${percision}`,
              format: 'decimal'
            }
          } else if(type === 'el-rate'){ //评分
            if(com['allow-half']){ //可以半个评分
              return {
                length: `16,1`,
                format: 'decimal'
              }
            }else{
              return {
                length: '0',
                format: 'int'
              }
            }
          }else if(com.__config__.numberType === 'percentage'){ // 如果是百分比
            return {
                length: `16,1`,
                format: 'decimal'
              }
          }else{
            //整数类型
            return {
              length: '0',
              format: 'int'
            }
          }
        } else {
          return {
            length: '50',
            format: 'varchar'
          }
        }
      },
      //根据字段配置生成校验规则
      getRule(item, field) {
        //不添加默认校验规则
        if (noRules.includes(field.__config__.tagIcon)) {
          return false
        } else if (item.format === 'varchar') {
          //文本类型，添加默认字符长度校验
          return {
            validator: `(rule,value,callback) => {
              if(value){
                 var count = 0
                 for (var i=0;i<value.length;i++) {
                    count +=value.charCodeAt(i) <=128 ? 1 : 2
                  }
                 if (count<=${Number(item.length)}) {
                   callback()
                  } else {
                    callback(new Error('字符长度不能超过${item.length}'))
                  }
              } else {
                callback()
              }
            }`
          }
        } else if (item.format === 'int') {
          //整数类型，添加默认数值大小校验
          return {
            validator: `(rule,value,callback) => {
              if(value){
                 var count = Number(value)
                 if(count<=2147483647&&count>=-2147483648){
                    callback()
                  } else {
                    callback(new Error('整数应在[-2147483648,2147483647]范围内'))
                  }
               } else {
                 callback()
               }
            }`
          }
        } else if (item.format === 'datetime') {
          if (!field.format) { //非日期时间组件
            //添加默认日期时间校验
            return {
              pattern: `/^[1-9][0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\\s+(20|21|22|23|[0-1][0-9]):[0-5][0-9]:[0-5][0-9]$/`,
              message: '请输入yyyy-MM-dd HH:mm:ss格式日期时间'
            }
          }
        } else if (item.format === 'time') {
          if (!field.format) { //非时间组件
            //添加默认时间校验
            return {
              pattern: `/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/`,
              message: '请输入HH:mm:ss格式时间'
            }
          }
        } else if (item.format === 'double' ||item.format === 'decimal') {
          //小数类型，添加默认长度和小数精度校验
          let nums = item.length.split(',')
          return {
            // let pattern = /^[0-9]*(\\.[0-9]*){0,1}$/
            validator: `(rule,value,callback) => {
              if (value) {
                let pattern = /^-?[0-9]*(\\.[0-9]*)?$/
                if (!pattern.test(value)) {
                    callback(new Error('请输入小数'))
                } else if (value.toString().length > ${Number(nums[0])}) {
                    callback(new Error('总长度不能超过${nums[0]}'))
                } else {
                    let parts = value.toString().split('.')
                    if (parts.length > 1 && parts[1].length > ${Number(nums[1])}) {
                    callback(new Error('小数最大精度为${nums[1]}'))
                    } else {
                    callback()
                    }
                }
              } else {
                callback()
              }
            }`
          }
        } else {
          return false
        }
      },
      //根据表单设计器组件列表自动生成数据库字段数组
      getAllFields(data) {
        if (data.length === 0) return
        if (!this.formInfo.id) { //新增表单
          data.filter((item) => { //过滤标题和分割线组件
            return item.__config__.tag !== 'TitleLine'
          }).map((item) => {
            if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
              //布局组件，遍历内部子组件
              item.__config__.children.map((c) => {
                this.getAllFields(c.__config__.children)
              })
            } else if (item.__config__.tag === 'Subform') {
                let newTableObj = {
                    tableName: item.__vModel__ ? item.__vModel__ : this.makeTableName(),
                    tableRemark: item.__config__.label,
                    fieldData: [],
                }
                item.__config__.children[0].__config__.children.forEach(comp => {
                    let { length,format } = this.getTypeDefault(comp,comp.__config__.tag, comp.__config__.tagIcon, comp.precision, comp['value-format'])
                    let newField
                    if(comp.__config__.tag === 'el-number'){
                      newField = {
                        name: comp.__vModel__,
                        length: length,
                        format: format,
                        desc: comp.__config__.label,
                        decimalPlaces: comp.__config__.decimalPlaces
                      }
                    }else{
                      newField = {
                        name: comp.__vModel__,
                        length: length,
                        format: format,
                        desc: comp.__config__.label
                      }
                    }
                    newTableObj.fieldData.push(newField)
                })
                this.formInfo.subFormListData.push(newTableObj)
            } else { //普通组件
              //根据组件类型获取默认长度和默认数据类型
              let {
                length,
                format
              } = this.getTypeDefault(item,item.__config__.tag, item.__config__.tagIcon, item.precision,item['value-format'])
              //在表结构数组中添加字段
              this.formInfo.fieldData.push({
                name: item.__vModel__,
                length: length,
                format: format,
                desc: item.__config__.label
              })
            }
          })
        } else { //编辑修改表单
          data.filter((item) => {
            return item.__config__.tag !== 'TitleLine' //过滤标题和分割线组件
          }).map((item) => {
            if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
             //布局组件，遍历内部子组件
             item.__config__.children.map((c) => {
                this.getAllFields(c.__config__.children)
              })
            } else if (item.__config__.tag === 'Subform' && item.__config__.children.length > 0) {
              const editTableList = this.formEditTableData
                let newTableObj = {
                    // 有可能是编辑进入的表单，但是子表单组件是新加的
                    tableName: item.__vModel__ ? item.__vModel__ : this.makeTableName(),
                    tableRemark: item.__config__.label,
                    fieldData: [],
                    renderKey: item.__config__.renderKey,
                    tableId: editTableList.filter((_) => _.tableName == item.__vModel__)[0]?.id
                }
                // let addTableFields = []
                item.__config__.children[0].__config__.children.forEach(comp => {
                    if (comp.isCreated) { //已创建的原始组件
                        let fieldData = this.formEditData.filter((field) => {
                            return field.name === comp.oldData.name
                        })
                        //拿到原始字段长度和数据类新，赋值，便于后面判断是否修改长度和数据类型
                        if (fieldData.length > 0) {
                            let origin
                            if( comp.__config__.tag === 'el-number'){
                              origin = {
                                desc: comp.__config__.label,
                                name: comp.__vModel__,
                                oldName: comp.__vModel__,
                                oldLength: fieldData[0].length,
                                oldType: fieldData[0].format,
                                length: fieldData[0].length,
                                format: fieldData[0].format,
                                decimalPlaces: comp.__config__.decimalPlaces
                              }
                            }else{
                              origin = {
                                desc: comp.__config__.label,
                                name: comp.__vModel__,
                                oldName: comp.__vModel__,
                                oldLength: fieldData[0].length,
                                oldType: fieldData[0].format,
                                length: fieldData[0].length,
                                format: fieldData[0].format,
                              }
                            }

                            //在表结构数组中添加字段
                            newTableObj.fieldData.push(origin)
                        }
                    } else {
                        let { length,format } = this.getTypeDefault(comp,comp.__config__.tag, comp.__config__.tagIcon, comp.precision, comp['value-format'])
                        let newField
                         if( comp.__config__.tag === 'el-number'){
                            newField = {
                              name: comp.__vModel__,
                              length: length,
                              format: format,
                              desc: comp.__config__.label,
                              decimalPlaces: comp.__config__.decimalPlaces
                          }
                         }else{
                          newField = {
                            name: comp.__vModel__,
                            length: length,
                            format: format,
                            desc: comp.__config__.label,
                            isTagChange: comp.isTagChange
                          }
                         }
                        // addTableFields.push(newField) //新增字段数组中添加字段
                        newTableObj.fieldData.push(newField)
                    }
                })
                // this.addTableFieldsMap.set(newTableObj.tableName, addTableFields)
                this.formInfo.subFormListData.push(newTableObj)
            } else {
                //普通组件
              if (item.isCreated) { //已创建的原始组件
                let fieldData = this.formEditData.filter((field) => {
                  return field.name === item.oldData.name
                })
                //拿到原始字段长度和数据类新，赋值，便于后面判断是否修改长度和数据类型
                if (fieldData.length > 0) {
                    if(item.__config__.tag === 'el-number' && item.__config__.decimalPlaces > 0){ //小数
                      let {
                        length,
                        format
                      } =this.getTypeDefault(item,item.__config__.tag, item.__config__.tagIcon, item.__config__.decimalPlaces)
                      let origin = {
                        desc: item.__config__.label,
                        name: item.__vModel__,
                        oldLength: fieldData[0].length,
                        oldType: fieldData[0].format,
                        length: length,
                        format: format,
                      }
                      //在表结构数组中添加字段
                      this.formInfo.fieldData.push(origin)
                    }else{
                        let origin = {
                        desc: item.__config__.label,
                        name: item.__vModel__,
                        oldLength: fieldData[0].length,
                        oldType: fieldData[0].format,
                        length: fieldData[0].length,
                        format: fieldData[0].format,
                      }
                      //在表结构数组中添加字段
                      this.formInfo.fieldData.push(origin)
                      }
                }
              } else { //新加字段
                //根据组件类型获取默认长度和默认数据类型
                let {
                  length,
                  format
                } = this.getTypeDefault(item,item.__config__.tag, item.__config__.tagIcon, item.precision,item['value-format'])
                let newField = {
                    name: item.__vModel__,
                    length: length,
                    format: format,
                    desc: item.__config__.label,
                    isTagChange: item.isTagChange
                }
                this.addFields.push(newField) //新增字段数组中添加字段
                this.formInfo.fieldData.push(newField) //在表结构数组中添加字段
              }
            }
          })
        }
      },
      //从第三步返回第二步，更新表单设计器各个组件的字段名称
      updateFieldName(data) {
        if (data.length === 0) return
        data.filter((item) => {
          return item.__config__.tag !== 'TitleLine' //过滤标题和分割线组件
        }).map((item) => {
          if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
            //布局组件，遍历内部子组件
            let tem = item.__config__.children.map((c) => {
              this.updateFieldName(c.__config__.children)
            })
          } else if (item.__config__.tag === 'Subform') {
            // this.formInfo.subFormListData.forEach(table => {
            //     item.__vModel__ = table.tableName
            //     item.__config__.label = table.tableRemark
            //     // this.num++
            // })
          } else {
            item.__vModel__ = this.formInfo.fieldData[this.num]?.name  //更新组件名称
            item.__config__.label = this.formInfo.fieldData[this.num]?.desc  //更新组件标签
            this.num++  //需存数据到数据库的组件数加一
          }
        })
      },
      //提交时添加默认规则，更新状态
      updateJsonRule (data) {
        if (data.length === 0) return
        data.filter((item) => {
          return item.__config__.tag !== 'TitleLine'  //过滤标题和分割线组件
        }).map((item, index) => {
          if (item.__config__.tag === 'el-card' || item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
            //布局组件，遍历内部子组件
            let tem = item.__config__.children.map((c) => {
              this.updateJsonRule(c.__config__.children)
            })
          } else if (item.__config__.tag === 'Subform') {
            let curData = this.formInfo.subFormListData[this.tableNum]
            const tableChildren = item.__config__.children[0].__config__.children
            let alterTableData = []
            let addTableFields = []
            curData.fieldData.forEach((fieldItem, idx) => {
                let newItem = tableChildren[idx]
                let rule = this.getRule(fieldItem, tableChildren[idx])
                if (rule) {
                    if (!newItem.isCreated) { //未创建
                        tableChildren[idx].__config__.regList.push(rule)
                    } else {
                        let exitIndex = ''
                        tableChildren[idx].__config__.regList.forEach((reg, index) => {
                            if (reg.validator) {
                                exitIndex = index
                            }
                        })
                        if (exitIndex !== '') {
                            tableChildren[idx].__config__.regList[exitIndex] = rule  //更新默认validator规则
                        }
                    }
                }
                if (newItem.isCreated) {
                    this.allNum++  //原始字段数加一
                    let temp = this.formEditData.filter((data) => {
                        return data.name === newItem.oldData.name
                    })
                    if (temp.length > 0) {
                        temp[0].isExist = true
                    }
                    if (fieldItem.format !== newItem.oldData.format) { //修改字段类型
                        this.isDeleteTableField = true  //需删除重构
                    }
                    if (fieldItem.name !== newItem.oldData.name || fieldItem.format !== newItem.oldData.format ||
                    fieldItem.length !== newItem.oldData.length || fieldItem.desc !== newItem.oldData.desc) { //字段名、长度、描述修改
                        alterTableData.push({
                            desc: fieldItem.desc,
                            format: fieldItem.format,
                            length: fieldItem.length,
                            name: newItem.oldData.name,
                            newName: fieldItem.name,
                            renderKey: item.__config__.renderKey
                        })
                        if (this.isReference === 1) {
                            this.updateJsonMessage(newItem.oldData.name, fieldItem.name)
                        }
                    }
                } else {
                    let newField = {
                        desc: fieldItem.desc,
                        format: fieldItem.format,
                        length: fieldItem.length,
                        name: fieldItem.name,
                        renderKey: item.__config__.renderKey,
                        isTagChange: fieldItem.isTagChange
                    }
                    addTableFields.push(newField) //新增字段数组中添加字段
                }
            })
            item.__vModel__ = curData.tableName
            item.__config__.label = curData.tableRemark
            // 有更新有新增存储
            addTableFields.length > 0 && this.addTableFieldsMap.set(curData.tableName, addTableFields)
            alterTableData.length > 0 && this.alterTableDataMap.set(curData.tableName, alterTableData)
            this.tableNum++
          } else { //普通组件
            //获取默认校验规则
            let rule = this.getRule(this.formInfo.fieldData[this.num], item)
            if (rule) { //有默认规则
              if (!item.isCreated) { //未创建，新加的组件
                item.__config__.regList.push(rule) //在规则列表配置中添加校验规则
              } else {
                let exitIndex = '' //默认validator规则在规则列表中的索引
                item.__config__.regList.forEach((reg, index) => {
                  if (reg.validator) {
                    exitIndex = index
                  }
                })
                if (exitIndex !== '') {
                    item.__config__.regList[exitIndex] = rule //更新默认validator规则
                }
              }
            }
            if (item.isCreated) { //已创建，原始组件字段
              this.allNum++  //原始字段数加一
              let temp = this.formEditData.filter((data) => {
                return data.name === item.oldData.name
              })
              if (temp.length > 0) {
                temp[0].isExist = true  //添加标识，原始字段存在
              }
              if (this.formInfo.fieldData[this.num].format !== item.oldData.format) { //修改字段类型
                this.isDeleteTableField = true //需删除数据重构表
              }
              if (this.formInfo.fieldData[this.num].name !== item.oldData.name ||
                this.formInfo.fieldData[this.num].desc !== item.oldData.desc || this.formInfo.fieldData[this
                  .num]
                .length !== item.oldData.length) { //字段名、长度、描述修改
                //在修改字段数组中添加字段信息
                this.alterData.push({
                  desc: this.formInfo.fieldData[this.num].desc,
                  format: this.formInfo.fieldData[this.num].format,
                  length: this.formInfo.fieldData[this.num].length,
                  name: item.oldData.name,
                  newName: this.formInfo.fieldData[this.num].name
                })
                if (this.isReference === 1) { //已发布，同步修改表单发布json对应字段名
                  this.updateJsonMessage(item.oldData.name, this.formInfo.fieldData[this.num].name)
                }
              }
              // else{
              //   // alert(1)
              //   this.alterData = []
              // }
            }
            item.__vModel__ = this.formInfo.fieldData[this.num]?.name
            item.__config__.label = this.formInfo.fieldData[this.num]?.desc
            this.num++ //在数据库中保存数据的组件的数量加一
          }
        })
      },
      //表单发布json同步更新字段名
      updateJsonMessage(oldName, newName) {
        let align = this.formJsonMessage.alignConfig.filter((item) => {
          return item.columnName === oldName
        })
        if (align.length > 0) {
          align[0].columnName = newName
        }
        let search = this.formJsonMessage.searchConfig.filter((item) => {
          return item.field === oldName
        })
        if (search.length > 0) {
          search[0].field = newName
        }
        if (this.formJsonMessage.rightConfig.leftConfig.field === oldName && this.formJsonMessage.rightConfig.leftConfig
          .table === this.tableName) {
          this.formJsonMessage.rightConfig.leftConfig.field = newName
          this.formJsonMessage.rightConfig.leftConfig.table = this.formInfo.nameData[0].tableName
        }
        if (this.formJsonMessage.rightConfig.sortConfig.field === oldName) {
          this.formJsonMessage.rightConfig.sortConfig.field = newName
        }
        let panel = this.formJsonMessage.rightConfig.panelConfig.filter((item) => {
          item.field === oldName
        })
        if (panel.length > 0) {
          panel[0].field = newName
        }
      },
      //表单发布json同步删除对应字段
      updateJsonMessageDel(name) {
        let align = this.formJsonMessage.alignConfig.findIndex((item) => {
          return item.columnName === name
        })
        if (align !== -1) {
          this.formJsonMessage.alignConfig.splice(align, 1)
        }
        let search = this.formJsonMessage.searchConfig.findIndex((item) => {
          return item.field === name
        })
        if (search !== -1) {
          this.formJsonMessage.searchConfig.splice(align, 1)
        }
        //  if(this.formJsonMessage.rightConfig.leftConfig.field === name) {
        //    this.formJsonMessage.rightConfig.leftConfig.field = ''
        //  }
        if (this.formJsonMessage.rightConfig.sortConfig.field === name) {
          this.formJsonMessage.rightConfig.sortConfig.field = ''
        }
        let panel = this.formJsonMessage.rightConfig.panelConfig.findIndex((item) => {
          item.field === name
        })
        if (panel !== -1) {
          this.formJsonMessage.rightConfig.panelConfig.splice(panel, 1)
        }
      },
      //表单发布json同步添加对应字段
      updateJsonMessageAdd() {
        let maxId = this.formJsonMessage.maxId
        let maxAlign = this.formJsonMessage.maxAlign
        let delIds = this.formJsonMessage.delIds
        let delAlign = this.formJsonMessage.delAlign
        let num1 = 0
        let num2 = 0
        // 全删全增
        this.addFields.forEach((item) => {
          if (delAlign.length > 0) {
            num1 = delAlign[0]
            delAlign.splice(0, 1)
          } else {
            num1 = maxAlign + 1
            maxAlign = num1
          }
          if (delIds.length > 0) {
            num2 = delIds[0]
            delIds.splice(0, 1)
          } else {
            num2 = maxId + 1
            maxId = num2
          }
          this.formJsonMessage.alignConfig.push({
            id: num1,
            columnName: item.name,
            sorting: true,
            align: "center",
            width: "",
          })
          this.formJsonMessage.searchConfig.push({
            id: num2,
            checked: true,
            category: "data",
            field: item.name,
            bindingTime: "不可绑定",
          })
        })
        this.addTableFieldsMap.forEach((vlist, key) => {
            vlist.forEach(tableItem => {
                this.formJsonMessage.alignConfig.push({
                    id: num1,
                    columnName: tableItem.name,
                    sorting: true,
                    align: "center",
                    width: "",
                    parentName: tableItem.tableRemark
                })
                // 子表单的查询配置
                this.formJsonMessage.searchConfig.push({
                    id: num2,
                    checked: true,
                    category: "data",
                    field: tableItem.name,
                    bindingTime: "不可绑定",
                })
            })
        })
        this.formJsonMessage.maxId = maxId
        this.formJsonMessage.maxAlign = maxAlign
        this.formJsonMessage.delIds = delIds
        this.formJsonMessage.delAlign = delAlign
      },
      //编辑时,更改json，添加字段标识
      updateJsonStatus(data) {
        if (data.length === 0) return
        data.filter((item) => {
          return item.__config__.tag !== 'TitleLine'  //过滤标题和分割线组件
        }).map((item) => {
          if (['Subform', 'el-card', 'el-tabs', 'Steps', 'el-collapse'].includes(item.__config__.tag)) {
          //布局组件，遍历内部子组件
           let tem = item.__config__.children.map((c) => {
                this.updateJsonStatus(c.__config__.children)
            })
          } else {
            // 查找到对应的olddata，不能根据 num 顺序取
            const curObj = this.formEditData.find(obj => {
                return obj.name === item.__vModel__
            })
            item.oldData = {
              ...curObj
            } //原始字段数据备份
            item.isCreated = true //添加标识，表示已创建，原始数据
            this.num++  //在数据库中存数据的组件数量加一
          }
        })
      },
      //表单设计：下一步/上一步
      nextStep(flag) {
        if (flag === 'plus') { //下一步
          if (this.stepNum === 1) {
            this.$refs.basicForm.validate((valid) => { //校验步骤一数据
              if (valid) {
                this.newFormName = this.formInfo.basic.formName
                this.stepNum++
                return true
              } else {
                return false
              }
            })
          } else if (this.stepNum === 2) {
            // const flag = this.$store.state.currentStep.fieldFlag  //判断是否有重复字段，有的话不能下一步
            // if(flag){
            //   return
            // }

            //字段名重复和空值校验
            let comArr = [] //所有组件属性值组成的数组
            this.$refs.design.drawingList.forEach((item,index)=>{
              if(['Steps', 'el-tabs', 'el-collapse','el-card','Subform'].includes(item.__config__.tag)){
                //布局型组件--选项卡/折叠面板/卡片/步骤条
                item.__config__.children && item.__config__.children.map((layout,index)=>{
                  layout.__config__.children && layout.__config__.children.map((layoutItem,index)=>{
                    comArr.push(layoutItem)
                  })
                })
              }else{
                //正常组件
                comArr.push(item)
              }
            })

            //获取重复元素
            let key = {} //存储的 key 是type的值，value是在indeces中对应数组的下标
            let indices = [] //数组中每一个值是一个数组，数组中的每一个元素是原数组中相同type的下标
            for(let i=0;i<comArr.length;i++){
              if(!comArr[i].__vModel__){
                this.$message.warning(comArr[i].__config__.label+'的字段名不能为空')
                return
              }
              //根据对应字段 字段名
              let __vModel__= comArr[i].__vModel__
              let _index = key[__vModel__]
              if (_index !== undefined) {
                indices[_index].push(i)
              } else {
                key[__vModel__] = indices.length
                indices.push([i])
              }
            }
            // 归类结果
            let result = []
            for(let i=0;i<indices.length;i++){
              if(indices[i].length>1){
                let str = [] //组件标题数组
                indices[i].forEach((index) => {
                  str.push(comArr[index]?.__config__?.label)
                })
                this.$message.warning(str +'的' +comArr[indices[i][0]].__vModel__+'字段名重复,请重新输入')
                return
              }
            }

            this.formInfo.subFormListData = []
            const filterTag = ['Subform', 'TitleLine', 'TitleLine', 'el-tabs', 'Steps', 'el-collapse', 'el-card']
            const list = this.$refs.design.drawingList.filter(comp => {
                return !filterTag.includes(comp.__config__.tag)
            })
            if (this.$refs.design.drawingList.length === 0) { //空组件
              this.$message.warning('请添加组件')
            } else if (list.length === 0) {
                return this.$message.warning('设计中未包含主表字段组件')
            } else {
              this.configPage.pageNo = 1
              if (!this.formInfo.nameData[0].tableName) { //表名为空，则自动生成表名
                this.formInfo.nameData[0].tableName = this.makeTableName() //随机生成表名
              }
              this.formInfo.nameData[0].tableRemark = this.formInfo.basic.formName  // 使用表单名称作为主表的备注
              if (!this.formInfo.id) { //新增
                this.formInfo.fieldData = []
                this.getAllFields(this.$refs.design.drawingList)  //根据表单组件自动生成数据库表结构
              } else { //编辑
                this.addFields = []
                this.addTableFieldsMap = new Map()
                this.formInfo.fieldData = []
                this.num = 0
                this.getAllFields(this.$refs.design.drawingList) //根据表单组件自动生成数据库表结构
              }
              this.$nextTick(() => {
                  this.updateFlag = Date.now()
              })
              this.showTableSetting = true
              // 等数据组装完成之后再添加展开的key
              this.expandKeys.push(this.formInfo.basic.formName)
              this.formInfo.formJsonUser = {
                fields: this.$refs.design.drawingList,
                ...this.$refs.design.formConf
              }
              this.stepNum++
              setTimeout(()=>{
                this.validateForm()  //自动校验
              },1000)
            }
          }
        } else { //上一步
          if (this.stepNum === 3) {
            this.num = 0
            this.updateFieldName(this.$refs.design.drawingList) //第二步的字段名、标签与第三步的名字、描述同步
            // 更新子表单的字段名
            const _this = this
            if (this.formInfo.subFormListData.length > 0) {
                let curTableNum = 0
                _this.$refs.design.drawingList.forEach(comp => {
                    if (comp.__config__?.tag === 'Subform') {
                        comp.__vModel__ = _this.formInfo.subFormListData[curTableNum].tableName
                        comp.__config__.children[0].__config__.children.forEach((fieldComp, idx) => {
                            // 更新字段名称
                            fieldComp.__vModel__ = _this.formInfo.subFormListData[curTableNum].fieldData[idx]?.name
                        })
                        curTableNum++
                    }
                })
            }
            this.configPage.pageNo = 1
          }
          this.stepNum--
        }
      },
      //新增/编辑表单分类--保存
      saveType() {
        this.$refs.typeNewForm.validate((valid) => {
          if (valid) {
            this.formTypeNew.categorySpell = Pinyin.GetJP(this.formTypeNew.categoryName)
              .toLowerCase() //简拼
            if (this.formTypeNew.id) { //编辑
              editCategory(this.formTypeNew).then((res) => {
                if (res.code === 0) {
                  this.$message.success('修改成功')
                  this.$refs.typeNewForm.resetFields()
                  this.dialogTypeVisible = false
                  this.tableTypeLoading = true
                  this.getTypeList()
                  this.getTypes() //更新左侧菜单
                }
              }).catch(e => console.log('编辑表单分类：', e))
            } else { //新增
              addCategory(this.formTypeNew).then((res) => {
                if (res.code === 0) {
                  this.$message.success('保存成功')
                  this.$refs.typeNewForm.resetFields()
                  this.dialogTypeVisible = false
                  this.tableTypeLoading = true
                  this.typePage.pageNo = 1
                  this.getTypeList()
                  this.getTypes() //更新左侧菜单
                }
              }).catch(e => console.log('新增表单信息：', e))
            }
          } else {
            return false
          }
        })
      },
      //打开表单分类新增/编辑窗口
      editType(row) {
        this.formTypeNew = {
          id: row ? row.id : '',
          categoryName: row ? row.categoryName : '',
          // categoryCode: row ? row.categoryCode : '',
          categorySpell: row ? row.categorySpell : '',
          categoryOrder: row ? row.categoryOrder : 0,
          categoryRemarks: row ? row.categoryRemarks : ''
        }
        this.categoryName = row ? row.categoryName : ''
        // this.categoryCode = row ? row.categoryCode : ''
        this.dialogTypeVisible = true
      },
      //删除表单分类
      delType(row) {
        this.$confirm('是否确认删除', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            ...this.page,
            formName: this.searchText,
            categoryId: row.id
          }
          getPageFormInfo(params).then((res) => {
            if (res.code === 0) {
              if (res.data.total > 0) { //分类下有表单
                this.$confirm('该分类下存在表单，是否确认删除', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  delCategory(row.id).then(res => {
                    if (res.code === 0) {
                      this.$message.success('删除成功')
                      // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
                      if (this.typePage.pageNo > 1 && (this.typePageTotal - 1) <= (this
                          .typePage
                          .pageNo -
                          1) * this.typePage.pageSize) {
                        this.typePage.pageNo--
                      }
                      this.tableTypeLoading = true
                      this.getTypeList()
                      this.getTypes() //更新左侧菜单
                    }
                  }).catch(e => console.log('删除表单分类：', e))
                })
              } else {
                delCategory(row.id).then(res => {
                  if (res.code === 0) {
                    this.$message.success('删除成功')
                    // 返回到原记录所在页面，而当原记录所在页不存在时，则返回上一页
                    if (this.typePage.pageNo > 1 && (this.typePageTotal - 1) <= (this.typePage
                        .pageNo - 1) *
                      this.typePage.pageSize) {
                      this.typePage.pageNo--
                    }
                    this.tableTypeLoading = true
                    this.getTypeList()
                    this.getTypes() //更新左侧菜单
                  }
                }).catch(e => console.log('删除表单分类：', e))
              }
            }
          }).catch(e => {
            console.log('分页获取表单信息:', e)
          })
        })
      },
      //关键字搜索
      searchChange() {
        this.searchFormData = reorganizationParam({name:this.searchText})
        this.page.pageNo = 1
        this.getList()
      },
      //重置搜索
      resetSeach(){
        this.searchFormData = {}
        this.searchText = '';
        this.getList();
      },
      //每页条数改变
      sizeChange(pageSize) {
        this.page.pageSize = pageSize
        this.page.pageNo = 1
        this.getList()
      },
      //页码改变
      currentChange(current) {
        this.page.pageNo = current
        this.getList()
      },
      //每页条数改变
      typeSizeChange(pageSize) {
        this.typePage.pageSize = pageSize
        this.typePage.pageNo = 1
        this.tableTypeLoading = true
        this.getTypeList()
      },
      //页码改变
      typeCurrentChange(current) {
        this.typePage.pageNo = current
        this.tableTypeLoading = true
        this.getTypeList()
      },
      //每页条数改变
      configSizeChange(pageSize) {
        this.configPage.pageSize = pageSize
        this.configPage.pageNo = 1
        if (this.formInfo.nameData.length > 0) {
            this.expandKeys = []
            this.expandKeys.push(this.formInfo.nameData[0].tableRemark)
        }
      },
      //页码改变
      configCurrentChange(current) {
        this.configPage.pageNo = current
        if (this.formInfo.nameData.length > 0) {
            this.expandKeys = []
            this.expandKeys.push(this.formInfo.nameData[0].tableRemark)
        }
      },
      //更新字段默认id
      updateFieldId(id) {
        this.fieldId = id
      },
      //时间戳转日期时间
      getDateTime(time) {
        let date = new Date(time)
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        return `${year}-${month<10?'0':''}${month}-${day<10?'0':''}${day} ${hour<10?'0':''}${hour}:${minute<10?'0':''}${minute}:${second<10?'0':''}${second}`
      },
      //生成随机数
      getRandomStr(len) {
        var str = "";
        for (let i = 0; i < len; i++) {
          str += Math.ceil(Math.random() * 10)
        }
        return str
      },
      makeTableName () {
        let date = new Date(Date.now())
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let hour = date.getHours()
        let minute = date.getMinutes()
        let second = date.getSeconds()
        const tt = 'table' + year + month + day + hour + minute + second + this.getRandomStr(5)
        return tt
      },
      //更改数据格式
      changeFormat(val,index) {
        if (val === 'varchar') {
          this.currentLength.length = '50'
        } else if (val === 'double' || val ==='decimal') {
          this.currentLength.length = `16,${this.$refs.design.drawingList[index].__config__.decimalPlaces == 0 || this.$refs.design.drawingList[index].__config__.decimalPlaces  == undefined? 2 : this.$refs.design.drawingList[index].__config__.decimalPlaces}`
        } else {
          this.currentLength.length = '0'
        }
      },
      //表单名校验
      formNameValidator(rule, value, callback) {
        if (value === this.formName) { //未修改
          callback()
        } else if (value.length > 200) {
          callback(new Error('表单名称长度不能超过200'))
        } else if (/^[\s\S]*.*[^\s][\s\S]*$/.test(value)) {
          getFormExist(value).then((res) => {
            if (res.code === 0) {
              if (res.data) {
                callback(new Error('表单名称已存在，请修改'))
              } else {
                callback()
              }
            }
          }).catch(e => console.log('根据表单名获取表：', e))
        } else {
          callback(new Error('不能为空，且不能仅包含空格'))
        }
      },
      //表名校验
      tableNameValidator(rule, value, callback) {
        // let pattern = /^[a-z][a-z_]{1,20}$/
        // let pattern = /^[a-zA-Z][^\u4e00-\u9fa5]+$/  //字母开头，不能有汉字，除开头字母以外至少还有一位
        let pattern = /^[a-z][^\u4e00-\u9fa5A-Z ]+$/ //字母开头，不能有汉字、大写字母、空格，除开头字母以外至少还有一位
        if (!pattern.test(value)) {
          callback(new Error('请输入符合要求的表名'))
        } else if (value.length > 64){
          callback(new Error('长度不能超过64'))
        } else {
          if (!this.formInfo.id) { //新增
            getTableListExcludeForm({ tableName: value}).then((res) => {
              if (res.code === 0 && res.data.includes(value.toLowerCase())) {
                callback(new Error('表名已存在，请修改'))
              } else {
                callback()
              }
            }).catch(e => console.log('获取所有表名：', e))
          } else {
            getTableListExcludeForm({ tableName: value, formId: this.formInfo.id }).then((res) => {
                if (res.code === 0 && res.data.includes(value.toLowerCase())) {
                    callback(new Error('表名已存在，请修改'))
                } else {
                    callback()
                }
            }).catch(e => console.log('获取除当前表单外的所有表名：', e))
          }
        }
      },
      //长度校验
      lengthValidator(rule, value, callback,row,item) {
        if(this.formInfo.formJsonUser.fields.filter((item)=>{return item.__vModel__ === row.name })
            && this.formInfo.formJsonUser.fields.filter((item)=>{return item.__vModel__ === row.name })[0]?.__config__.tagIcon === 'date-range' ||
          this.formInfo.formJsonUser.fields.filter((item)=>{return item.__vModel__ === row.name })
            && this.formInfo.formJsonUser.fields.filter((item)=>{return item.__vModel__ === row.name })[0]?.__config__.tagIcon === 'time-range'){ //日期范围 时间范围不校验
            callback()
        }
        let pattern = /^[1-9][0-9]*$/
        if (!pattern.test(value)) {
          callback(new Error('请输入数字'))
        } else {
          //当前行组件
         let element =  this.formInfo.formJsonUser.fields.filter((item)=>{return item.__vModel__ === row.name })
          let num = Number(value)
          if(element[0]&&element[0]['show-word-limit'] && value < Number(element[0].maxlength)){
            callback(new Error('长度不得小于限制输入字符长度'))
          } else if ( value > 1225) {
            callback(new Error('字符长度不能超过1225'))
          } else {
            if (this.isReference ) { //已发布
              if (this.currentLength.oldLength) {
                if (this.currentLength.oldType === this.currentLength.format) { //同类型
                  let oldNum = Number(this.currentLength.oldLength)
                  if (num < oldNum) {
                    this.currentLength.length = this.currentLength.oldLength
                  }
                }
              }
            }
            callback()
          }
        }
      },
      //长度校验
      lengthValidator1(rule, value, callback) {
        let pattern = /^[4]$/
        if (!pattern.test(value)) {
          callback(new Error('仅能为4'))
        } else {
          callback()
        }
      },
      //长度校验
      lengthValidator2(rule, value, callback) {
        let pattern = /^[0]$/
        if (!pattern.test(value)) {
          callback(new Error('仅能为0'))
        } else {
          callback()
        }
      },
      //长度校验
      lengthValidator3(rule, value, callback) {
        let pattern = /^[1-9][0-9]{0,2},[0-9]$/
        if (!pattern.test(value)) {
          callback(new Error('请输入“总长度,小数位数”'))
        } else {
          let nums = value.split(',')
          if (Number(nums[0]) > 255) {
            callback(new Error('总长度不能超过255'))
          } else {
            if (this.isReference) { //已发布
              if (this.currentLength.oldLength) {
                if (this.currentLength.oldType === this.currentLength.format) { //同类型
                  let oldNums = this.currentLength.oldLength.split(',')
                  let oldNum = Number(this.currentLength.oldLength)
                  let isLow = false
                  if (Number(nums[0]) < Number(oldNums[0])) {
                    nums[0] = oldNums[0]
                    isLow = true
                  }
                  if (Number(nums[1]) < Number(oldNums[1])) {
                    nums[1] = oldNums[1]
                    isLow = true
                  }
                  if (isLow) {
                    this.currentLength.length = nums.join(',')
                  }
                }

              }
            }
            callback()
          }
        }
      },
      //字段名校验
      fieldNameValidator(rule, value, callback) {
        let pattern = /^[a-z][^\u4e00-\u9fa5A-Z ]+$/
        if (!pattern.test(value)) {
          callback(new Error('请输入符合要求的字段名'))
        } else if (value.length > 64){
          callback(new Error('长度不能超过64'))
        } else {
          let names = this.formInfo.fieldData.filter((item) => {
            return item.name === value
          })
          if (names.length > 1) {
            callback(new Error('字段名重复'))
          } else {
            callback()
          }
        }
      },
      //排序校验
      sortValidator(rule, value, callback) {
        if (value > 10000) {
          callback(new Error('不能超过10000'))
        } else {
          callback()
        }
      },
      //表单分类名称校验
      typeNameValidator(rule, value, callback) {
        if (value === this.categoryName) { //未修改
          callback()
        } else {
          if (value.length > 200) {
            callback(new Error('名称长度不能超过200'))
          } else if (/^[\s\S]*.*[^\s][\s\S]*$/.test(value)) {
            getAllCategory().then((res) => {
              if (res.code === 0) {
                let names = res.data.map((item) => {
                  return item.categoryName
                })
                if (names.includes(value)) {
                  callback(new Error('表单分类名称已存在，请修改'))
                } else {
                  callback()
                }
              }
            }).catch(e => {
              console.log('获取所有表单分类：', e)
            })
          } else {
            callback(new Error('名称不能为空，且不能仅包含空格'))
          }
        }
      },
      //表单分类编码校验
      typeCodeValidator(rule, value, callback) {
        if (value === this.categoryCode) { //未修改
          callback()
        } else {
          getAllCategory().then((res) => {
            if (res.code === 0) {
              let codes = res.data.map((item) => {
                return item.categoryCode
              })
              if (codes.includes(value)) {
                callback(new Error('表单分类编码已存在，请修改'))
              } else {
                callback()
              }
            }
          }).catch(e => {
            console.log('获取所有表单分类：', e)
          })
        }
      },
      //校验数据结构表数据
      validateForm() {
        this.$refs.tableInfo.validate((valid) => {
          if (valid) {
            return true
          } else {
            return false
          }
        })
      }
    }
  }

</script>
<style lang="scss" scoped>
.demo-ruleForm {
  padding: 20px 0;
}
  .dotClass {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    display: block;
  }
  .app-container {
    .formDesigner {
      width: 100%;
      height: 100%;

      .managePage {
        display: flex;
        width: 100%;
        justify-content: space-between;
        // max-height: calc(100vh - 124px);

        .leftTypes {
          width: 245px;
          max-height: 100%;
          -webkit-box-shadow: 2px 0px 2px 0px rgb(0 0 0 / 7%);
          box-shadow: 2px 0px 2px 0px rgb(0 0 0 / 7%);
          margin: -20px 0 0 -20px;
          padding: 15px 0 0 20px;
          min-height: calc(100vh - 104px);
          .formTypeItems {
            max-height: calc(100vh - 170px);
            overflow-y: auto;

            .formTypeItem {
              padding: 10px 0px;

              .menuTitle {
                display: inline-block;
                width: 85%;
                padding-left: 5%;
                // text-align: center;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                font-size: 12px;
              }
            }

            .formTypeItem:hover {
              background: rgba(64, 158, 255, 0.1);
              color: #409EFF;
              border-right: 2px solid #409EFF;
              cursor: pointer;
            }
          }

          .active {
            background: rgba(64, 158, 255, 0.1);
            color: #409EFF;
            // border-right: 2px solid #409EFF;
          }

          .formTypeTitle {
            padding: 10px 0px;
            // text-align: center;
            background: #409EFF;
            color: white;
          }

          .formTypeEmpty {
            text-align: center;
            margin-top: 30%;
          }

        }

        .rightContent {
          width: calc(100% - 225px);
          height: 100%;
          padding-left: 20px;

          .keywordInput {
            width: 200px;
            margin-right: 8px;
          }

          .tableInfo {
            width: 100%;
            margin-bottom: 20px;
            // height:calc(100% - 110px);
            max-height: calc(100% - 110px);
          }
        }
      }

      .designHeader {
        display: flex;
        justify-content: space-around;
        align-items: center;

        .designStep {
          display: flex;
          justify-content: center;
          width: 100%;
          margin-left: 10%;

          .designStepItem {
            width: 33.3%;
            display: flex;
            align-items: center;
            justify-content: space-around;

            .designStepLine {
              display: inline-block;
              width: calc(100% - 110px);
              height: 2px;
            }

            .designStepIndex {
              font-size: 16px;
              color: white;
              width: 30px;
              height: 30px;
              border-radius: 50%;
              text-align: center;
              line-height: 30px;
              margin-right: 5px;
              margin-left: 5px;
              font-weight: bold;
            }

            .designStepTitle {
              font-size: 14px;
              font-weight: bold;
              width: 70px;
            }
          }
        }
      }

      .basicInfo {
        margin-right: 15%;
        margin-left: 15%;
        margin-top: 5%;
      }

      .formConfig {
        margin-right: 15%;
        margin-left: 15%;
        margin-top: 35px;

        .tooltipText {
          font-size: 8px;
          padding-left: 100px;
          margin-top: 5px;
          margin-bottom: 10px;
        }

        .tooltipText2 {
          font-size: 8px;
          color: red;
          margin-bottom: 10px;
        }
      }
    }
  }

</style>
<style lang="scss">
  @import '@/styles/home';
    .tableForm{
      .el-table th.el-table__cell.is-leaf, .el-table td.el-table__cell{
        border-bottom: 0px !important;
      }
      .el-form-item{
        // margin-bottom: 10px !important;
        margin-top: 10px;
      }
    }
    .el-button--small{
      border-radius: 2px;
    }
    .formDesigner {
      .el-input__inner{
        border-radius: 2px;
      }
      .basicInfo .el-form-item{
        margin-bottom: 30px
      }
      .el-button{
        border-radius: 2px;
      }
    }
    .el-button.is-circle{
      border-radius: 50% !important;
    }
   .formDesigner .tableInfo {
    .el-table--border .el-table__cell:first-child .cell{
      padding-left:0px
    }
    .el-table__empty-block{
      border-bottom: 1px solid rgba(0,0,0,0.06);
      border-right: 1px solid rgba(0,0,0,0.06);
    }
    .el-table__header-wrapper th, .el-table__fixed-header-wrapper th{
      height: 48px;
    }
    .el-table__cell{
      height: 48px;
    }
    .el-table-column--selection .cell{
      padding-left: 0;
      padding-right: 0
    }
  }
  .el-drawer__header {
    border-bottom: 1px solid #e6e8eb;
    padding:10px 10px 10px 20px;
  }

  .el-dialog__header {
    display: flex;
    align-items: center;
    // margin: auto 0;
    padding:15px 15px 10px 20px;
    border-bottom: 1px solid #e8eaec;
  }
  .el-dialog__headerbtn {
    top: auto;
  }
  .formDesigner {
    .managePage {
      .el-table__cell {
        padding: 3px 0px;
      }
    }

    .el-table {
      box-sizing: border-box;

      &::before {
        height: 0px;
      }
    }

    .el-table--border::after,
    .el-table--group::after {
      width: 0px;
      height: 0px;
    }

    .formConfig {
      .el-form-item {
        margin-bottom: 20px;
      }

      .el-table__cell {
        // border-bottom: 0px;
        padding: 0px;
      }

      .el-table__body-wrapper {
        margin-top: 10px;
      }
    }
    .el-dialog__header{
      .el-dialog__headerbtn{
        font-size:20px;
      }
    }
    .el-dialog__body {
      padding-top: 0px;

      .el-table__cell {
        // border-bottom: 0px;
        padding: 3px 0px;
      }
    }

    // 当前行高亮颜色
    // .current-row > td {
    //   background: #b2c8df !important;
    //   // color: white;
    // }

    // 鼠标悬浮行颜色
    // tr:hover > td {
    //   background-color: #b2c8df !important;
    // }
  }

</style>
